Java对Redis基本使用
1 引入jar包
java是通过Jedis对redis进行操作的,首先引入jedis.jar
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2 建立redis连接池
import java.util.ArrayList;
import java.util.List; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool; public class RedisPool { // 非切片客户端链接对象
private Jedis jedis;
// 非切片链接池对象
private JedisPool jedisPool;
// 切片客户端链接对象
private ShardedJedis shardedJedis;
// 切片链接池
private ShardedJedisPool shardedJedisPool; private String ip = "127.0.0.1";
private int port = 6379; public RedisPool(){
initializePool();
initializeShardedPool();
setJedis(jedisPool.getResource());
setShardedJedis(shardedJedisPool.getResource());
} public RedisPool(String ip){
this.ip = ip;
initializePool();
initializeShardedPool();
setJedis(jedisPool.getResource());
setShardedJedis(shardedJedisPool.getResource());
} public RedisPool(String ip, int port){
this.ip = ip;
this.port = port;
initializePool();
initializeShardedPool();
setJedis(jedisPool.getResource());
setShardedJedis(shardedJedisPool.getResource()); } // 初始化非切片池
public void initializePool(){
//池的配置
JedisPoolConfig jpc = new JedisPoolConfig();
//最大空闲连接数
jpc.setMaxIdle(20);
jpc.setMaxIdle(5);
//获取连接时的最大等待毫秒数
jpc.setMaxWaitMillis(1000);
//在空闲时检查有效性, 默认false
jpc.setTestOnBorrow(false);
jedisPool = new JedisPool(jpc, ip, port);
} // 初始化切片池
public void initializeShardedPool(){
//池的配置
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(20);
config.setMaxWaitMillis(1000);
config.setTestOnBorrow(false);
// slave链接
//可以实现集群的功能,配置多个redis服务实现请求的分配进行负载均衡
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(ip, port, "master"));
// 构造池
shardedJedisPool = new ShardedJedisPool(config, shards);
} public void closeJedisPool(){
jedisPool.close();
}
public void closeShardedJedisPool(){
shardedJedisPool.close();
} public Jedis getJedis() {
return jedis;
} public void setJedis(Jedis jedis) {
this.jedis = jedis;
} public ShardedJedis getShardedJedis() {
return shardedJedis;
} public void setShardedJedis(ShardedJedis shardedJedis) {
this.shardedJedis = shardedJedis;
}
}
3 定义操作接口
import java.util.Map;
import java.util.Set; public interface IRedisService { public Boolean setString(String key, String value);
public String getString(String key);
public Boolean existsKey(String key);
public Long delKey(String key);
public String typeKey(String key);
public Set<String> keys(String key); /**
* 获得map数据集
* @param key
* @return
*/
public Map<String, String> getMap(String key); /**
* 设置map数据集
* @param key
* @param map
* @return
*/
public Boolean setMap(String key, Map<String, String> map); /**
* 获得map字段中的值
* @param key
* @param fieldKey
* @return
*/
public String getMapFieldValue(String key, String fieldKey); /**
* 获得map中多个字段值
* @param key
* @param fieldKeys
* @return
*/
public Map<String, String> getMapFieldValues(String key, String[] fieldKeys); /**
* 设置map中具体的字段值
* 参考存储格式:{key,map{fieldKey, fieldValue}}
* @param key
* @param fieldKey
* @param fieldValue
* @return
*/
public Boolean setMapFieldValue(String key, String fieldKey, String fieldValue); }
4 接口实现类
import java.util.HashMap;
import java.util.Map;
import java.util.Set; import com.robert.redis.client.config.RedisPool; import redis.clients.jedis.Jedis;
import redis.clients.jedis.ShardedJedis; public class RedisService implements IRedisService{ private RedisPool redisPool; public RedisService(){
redisPool = new RedisPool();
} public RedisService(String host){
redisPool = new RedisPool(host);
} public RedisService(String host, int port){
redisPool = new RedisPool(host, port);
} private Jedis getJResource(){
Jedis jResource = null;
jResource = redisPool.getJedis();
return jResource;
}
private ShardedJedis getShardResource(){
ShardedJedis sResource = null;
sResource = redisPool.getShardedJedis();
return sResource;
} public Boolean setString(String key, String value) {
boolean result = false;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
resource.set(key, value);
result = true;
} }catch(Exception e){
result = false;
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} public String getString(String key) {
String result = null;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
result = resource.get(key);
} }catch(Exception e){
result = null;
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} public Boolean existsKey(String key) {
Boolean result = false;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
result = resource.exists(key);
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
} return result;
} public Long delKey(String key) {
Long result = null;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
result = resource.del(key);
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} public String typeKey(String key) {
String result = null;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
result = resource.type(key);
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} public Set<String> keys(String key) {
Set<String> result = null;
Jedis resource = null;
try{
resource = getJResource();
if(resource != null){
result = resource.keys(key);
} }catch(Exception e){
result = null;
e.printStackTrace();
}finally{
redisPool.closeJedisPool();
}
return result;
} public Map<String, String> getMap(String key) {
Map<String, String> map = null;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null && resource.exists(key)){
map = resource.hgetAll(key);
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return map;
} public Boolean setMap(String key, Map<String, String> map) {
Boolean result = false;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
resource.hmset(key, map);
result = true;
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} public String getMapFieldValue(String key, String fieldKey) {
String result = null;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null && resource.hexists(key, fieldKey)){
result = resource.hget(key, fieldKey);
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} public Map<String, String> getMapFieldValues(String key, String[] fieldKeys) {
Map<String, String> map = new HashMap<String, String>();
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
for(String fieldKey : fieldKeys){
map.put(fieldKey, resource.hget(key, fieldKey));
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return map;
} public Boolean setMapFieldValue(String key, String fieldKey, String fieldValue) {
Boolean result = false;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null && resource.exists(key)){
resource.hset(key, fieldKey, fieldValue);
result = true;
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} }
5 测试
public static void main( String[] args )
{ IRedisService rs = new RedisService();
rs.setString("test", "Hello Redis!");
System.out.println(rs.getString("test"));
}
Java对Redis基本使用的更多相关文章
- java操作redis之jedis篇
首先来简单介绍一下jedis,其实一句话就可以概括的,就是java操作redis的一种api.我们知道redis提供了基本上所有常用编程语言的clients,大家可以到http://redis.io/ ...
- Java连接redis的使用演示样例
Java连接redis的使用演示样例 Redis是开源的key-value存储工具,redis通经常使用来存储结构化的数据,由于redis的key能够包括String.hash.listset和sor ...
- Java的redis 操作类-优化通用版本
java操作redis多节点处理方式;http://blog.itpub.net/29254281/viewspace-1188644/首先maven引入依赖包 <dependency> ...
- redis学习心得之三-【java操作redis】
今天主要是讲讲java对redis的操作,来段代码掩饰下基本操作即可明白. java调用你需要下载jedis.jar包 下载网址:https://github.com/xetorthio/jedis/ ...
- java 操作redis
使用Java操作Redis需要jedis-2.1.0.jar,如果需要使用Redis连接池的话,还需commons-pool-1.5.4.jar package com.test; import ja ...
- java操作redis redis连接池
redis作为缓存型数据库,越来越受到大家的欢迎,这里简单介绍一下java如何操作redis. 1.java连接redis java通过需要jedis的jar包获取Jedis连接. jedis-2.8 ...
- java 操作 redis
1.Java 使用 Redis 只需要下载一个jar包即可 地址:http://maven.outofmemory.cn/redis.clients/jedis/2.5.2/ 工程
- java 使用redis 数据库
[TOC] java 使用redis 数据库 连接redis package com.wsc.redis.Test1; import java.util.List; import java.util. ...
- windows下Redis安装及利用java操作Redis
一.windows下Redis安装 1.Redis下载 下载地址:https://github.com/MicrosoftArchive/redis 打开下载地址后,选择版本 然后选择压缩包 下载 R ...
- Java使用Redis实现分布式锁来防止重复提交问题
如何用消息系统避免分布式事务? - 少年阿宾 - BlogJavahttp://www.blogjava.net/stevenjohn/archive/2018/01/04/433004.html [ ...
随机推荐
- docker大全集
1,什么是docker docker 最初是dotCloud公司创始人 Solomon Hykes 在法国期间发起的一个公司内部醒目,于 2013年 3 月以 Apache 2.0 授权协议开源, 主 ...
- apple IOS的base64编解码
<pre style="word-wrap: break-word; white-space: pre-wrap;">/* * Copyright (c) 2003 A ...
- bzoj1007 [HNOI2008]水平可见直线——单调栈
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1007 可以把直线按斜率从小到大排序,用单调栈维护,判断新直线与栈顶的交点和栈顶与它之前直线的 ...
- Center OS Tomcat7 服务器配置总结
tomcat7 目录结构 --- webapps 应用存放目录,可以配置Host 来决定这个文件的目录,可以配置多个Host,多个webapps ---ROOT 项目根目录,Tomcat会特殊对待这个 ...
- HDU 5903 Square Distance (贪心+DP)
题意:一个字符串被称为square当且仅当它可以由两个相同的串连接而成. 例如, "abab", "aa"是square, 而"aaa", ...
- Android系统中setprop,getprop,watchprops命令的使用(转载)
转自:http://blog.csdn.net/yao_guet/article/details/6531241 在android系统中,有一些初始化的配置文件,例如: /init.rc /defau ...
- bzoj 1017: [JSOI2008]魔兽地图DotR【树形dp+背包】
bzoj上是一个森林啊--? dp还是太弱了 设f[i][j][k]为到点i,合成j个i并且花费k金币能获得的最大力量值,a[i]为数量上限,b[i]为价格,p[i]为装备力量值 其实这个状态设计出来 ...
- bzoj 4817: [Sdoi2017]树点涂色【树链剖分+LCT】
非常妙的一道题. 首先对于操作一"把点x到根节点的路径上所有的点染上一种没有用过的新颜色",长得是不是有点像LCT中的access操作?进而发现,如果把同一颜色的点连起来作为LCT ...
- 第三篇(那些JAVA程序BUG中的常见单词)
illegal modifier for parameter xxx; only final is permitted 参数xxx的修饰符非法:只允许final illegal 非法的 modifie ...
- java 调用动态库打包sdk
java连接c++动态库并生成jar包提供给别人调用 1.需要将java通过jni生成头文件,并导入到c++项目并对c++进行jni方法继承 在项目的src目录执行,否则会提示 错误:找不到符号 ja ...