pom jar包引用
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.1</version>
</dependency>
简单使用
Jedis jedis = new Jedis("192.168.1.3",6379); //连接redis
//使用redis命令
jedis.ping();
jedis.set("k1", "v1");
jedis.get("k1");
Map<String, String> h1 = new HashMap<>();
h1.put("id", "1");
h1.put("name", "zhangsan");
jedis.hset("h1", h1);
Transaction transaction = jedis.multi(); //开启事务
transaction.set("k2", "v2");
transaction.set("k3", "v3");
transaction.exec(); //提交事务
jedis.set("balance", "100");
jedis.watch("balance"); // 开启监视,加锁
Integer balance = Integer.parseInt(jedis.get("balance"));
if (balance < 0) {
jedis.unwatch(); // 取消监视
System.out.println("余额不够");
} else {
// 开启事务....代码省略
}
使用连接池
package fg.jedis.demo;
import redis.clients.jedis.JedisPool;
public class JedisPoolUtil {
private static volatile JedisPool JedisPool = null;
private JedisPoolUtil(){}
public static JedisPool getJedisPoolInstance() {
if (JedisPool == null) {
synchronized (JedisPoolUtil.class) {
if (JedisPool == null) {
//pool配置参考:https://yq.aliyun.com/articles/236383?spm=a2c4e.11153959.blogcont531067.14.64f445b52u5nWH
//JedisPoolConfig poolConfig = new JedisPoolConfig();
//return new JedisPool(poolConfig,"192.168.1.3", 6379);
return new JedisPool("192.168.1.3", 6379);
}
}
}
return JedisPool;
}
}
public static void main(String[] args) {
Jedis jedis = null;
try {
JedisPool jedisPool = JedisPoolUtil.getJedisPoolInstance();
jedis = jedisPool.getResource();
jedis.set("k1", "v1");
System.out.println(jedis.get("k1"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close(); //如果有连接池,close会归还连接
}
}
}
使用集群
public static void main(String[] args) {
//创建集群节点
Set<HostAndPort> nodes = new HashSet<>();
nodes.add(new HostAndPort("192.168.1.4", 7000));
nodes.add(new HostAndPort("192.168.1.4", 7001));
nodes.add(new HostAndPort("192.168.1.4", 7002));
nodes.add(new HostAndPort("192.168.1.4", 7003));
nodes.add(new HostAndPort("192.168.1.4", 7004));
nodes.add(new HostAndPort("192.168.1.4", 7005));
// Jedis连接池配置
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(100); // 最大空闲连接数, 默认8个
jedisPoolConfig.setMaxTotal(500); // 最大连接数, 默认8个
jedisPoolConfig.setMinIdle(0); //最小空闲连接数, 默认0
// 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间, 默认-1
jedisPoolConfig.setMaxWaitMillis(2000); // 设置2秒
jedisPoolConfig.setTestOnBorrow(true); //对拿到的connection进行validateObject校验
JedisCluster jedisCluster = new JedisCluster(nodes,jedisPoolConfig); //创建集群对象
jedisCluster.set("k1", "v1");
System.out.println(jedisCluster.get("k1"));
jedisCluster.close(); //关闭集群对象,实际应该在应用程序停止后关闭
}
java操作redis常用方法
//我们定义成接口,实现类可以使用单机版、连接池、集群
public interface JedisClient {
String set(String key, String value); //添加key
String get(String key); //获取key
Boolean exists(String key); //key是否存在
Long expire(String key, int seconds); //设置key的过期时间
Long ttl(String key); //查看key的过期时间
Long incr(String key); //对key+1
Long hset(String key, String field, String value); //添加hash类型
String hget(String key, String field); //获取hash类型
Long hdel(String key,String... field);//删除hash类型的
}
使用举例
1、把登录用户下的权限和菜单添加到缓存中。这是可以使用hset("permission","userid","permissionToJsonString") 、hset("menu","userid","menuListToJsonString")
2、查询所有的机构信息,这时候可以使用set("jg","jgListToJsonString")
JedisClient与Spring整合
<bean class="redis.clients.jedis.JedisPool">
<constructor-arg name="host" value="192.168.1.3"></constructor-arg>
<constructor-arg name="port" value="6379"></constructor-arg>
</bean>
<bean class="xxx.JedisClientPool"></bean>
//该类已交给spring托管
//<bean class="xxx.JedisClientPool"></bean>
public class JedisClientPool implements JedisClient { //实现接口,里面定义了操作redis的常用方法
@Autowired
private JedisPool jedisPool;
@Override
public String set(String key, String value) {
Jedis jedis = jedisPool.getResource();
String result = jedis.set(key, value);
jedis.close();
return result;
}
@Override
public String get(String key) {
Jedis jedis = jedisPool.getResource();
String result = jedis.get(key);
jedis.close();
return result;
}
//省略代码
}
JedisCluster与Spring整合
<bean class="redis.clients.jedis.JedisCluster">
<constructor-arg name="nodes">
<set>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg name="host" value="192.168.25.153"></constructor-arg>
<constructor-arg name="port" value="7001"></constructor-arg>
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg name="host" value="192.168.25.153"></constructor-arg>
<constructor-arg name="port" value="7002"></constructor-arg>
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg name="host" value="192.168.25.153"></constructor-arg>
<constructor-arg name="port" value="7003"></constructor-arg>
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg name="host" value="192.168.25.153"></constructor-arg>
<constructor-arg name="port" value="7004"></constructor-arg>
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg name="host" value="192.168.25.153"></constructor-arg>
<constructor-arg name="port" value="7005"></constructor-arg>
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg name="host" value="192.168.25.153"></constructor-arg>
<constructor-arg name="port" value="7006"></constructor-arg>
</bean>
</set>
</constructor-arg>
</bean>
<bean class="xxx.JedisClientCluster"></bean>
//该类已交给spring托管
//<bean class="xxx.JedisClientCluster"></bean>
public class JedisClientCluster implements JedisClient { //实现接口,里面定义了操作redis的常用方法
@Autowired
private JedisCluster jedisCluster;
@Override
public String set(String key, String value) {
return jedisCluster.set(key, value);
}
@Override
public String get(String key) {
return jedisCluster.get(key);
}
//省略部分方法
}
使用Spring Data Redis
<!--2.x 以上版本需要jdk1.8 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.13.RELEASE</version>
</dependency>
<!-- 连接池配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="100" />
<property name="maxIdle" value="50" />
<property name="minIdle" value="10" />
<!-- 其他属性到源码中查看,这里我们使用默认值 -->
</bean>
<!-- 使用工厂创建连接 -->
<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="jedisPoolConfig" />
<property name="hostName" value="192.168.1.3" />
<property name="port" value="6379" />
<!-- <property name="password" value="123456" /> -->
<!-- 其他属性到源码中查看,这里我们使用默认值 -->
</bean>
<!-- 使用RedisTemplate,key value 的存储采用序列化,可以配置采用哪种序列化接口,这里我们使用默认配置-->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnFactory" />
</bean>
<!-- 使用StringRedisTemplate,key value 的存储全部使用string类型-->
<bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="jedisConnFactory" />
</bean>
@Autowired
RedisTemplate redisTemplate;
@Autowired
StringRedisTemplate stringRedisTemplate;
@RequestMapping("test1")
@ResponseBody
public String test1(){
stringRedisTemplate.opsForValue().set("k1", "v1"); //set
stringRedisTemplate.opsForValue().get("k1"); //get
stringRedisTemplate.opsForHash().put("dept","id","1"); //hset
stringRedisTemplate.opsForHash().put("dept","name","财务部"); //hset
stringRedisTemplate.opsForHash().entries("dept"); //hgetall dpet
stringRedisTemplate.opsForHash().get("dept", "id"); //hget dept id
return "suceess";
}