1. java操作redis
1.1 使用jedis
(1)添加jedis依赖
(2)代码测试
@Test
public void test01(){
//连接redis--->必须保证你的redis服务运行远程连接。
//该对象中把每个redis命令封装成对应的方法了。
Jedis jedis=new Jedis("192.168.223.155",6380);
//对于字符串操作的命令
String s = jedis.set("k1", "v1");
System.out.println(s);
String setex = jedis.setex("k2", 30l, "v2");
System.out.println(setex);
Long aLong = jedis.setnx("k3", "v11");
System.out.println(aLong);
//对于hash操作
jedis.hset("k4","name","ldh");
jedis.hset("k4","age","15");
Map<String,String> map=new HashMap();
map.put("name","zdd");
map.put("age","28");
jedis.hset("k5",map);
jedis.close();
}
1.2 使用连接池连接redis
public void test02(){
//创建连接池的配置类
JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(20);
jedisPoolConfig.setMinIdle(5);
jedisPoolConfig.setMaxWait(Duration.ofMillis(3000));
JedisPool jedisPool=new JedisPool(jedisPoolConfig,"192.168.223.155",6380);
long start=System.currentTimeMillis();
for (int i = 0; i <1000 ; i++) {
//从jedis连接池获取资源
Jedis jedis = jedisPool.getResource();
String ping = jedis.ping();
jedis.close();//是否资源到池子
}
long end=System.currentTimeMillis();
System.out.println("总耗时:"+(end-start));
}
<bean id="" class="JedisPoolConfig">
<property name="maxIdle" value="20">
</bean>
@Autowire
1.3 java连接redis集群模式
@Test
public void test03(){
Set<HostAndPort> nodes=new HashSet<>();
nodes.add(new HostAndPort("192.168.223.155",6001));
nodes.add(new HostAndPort("192.168.223.155",6002));
nodes.add(new HostAndPort("192.168.223.155",6003));
nodes.add(new HostAndPort("192.168.223.155",6004));
nodes.add(new HostAndPort("192.168.223.155",6005));
nodes.add(new HostAndPort("192.168.223.155",6006));
JedisCluster jedisCluster=new JedisCluster(nodes);
jedisCluster.set("k6","张三和李四");
jedisCluster.close();
}
2.springboot整合redis
springboot对redis的操作封装了两个StringRedisTemplate和RedisTemplate类,StringRedisTemplate是RedisTemplate的子类,StringRedisTemplate它只能存储字符串类型,无法存储对象类型。要想用StringRedisTemplate存储对象必须把对象转为json字符串。