1.maven坐标
<!--依赖Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<!--不依赖Redis的异步客户端lettuce -->
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--引入Redis的客户端驱动jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
客户端驱动:一般使用jedis,故将默认的驱动lettuce排除。
2.redis连接服务器配置
#redis配置连接池属性
spring.redis.jedis.pool.min-idle=5
spring.redis.jedis.pool.max-active=10
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.max-wait=2000
#redis配置服务器属性
spring.redis.port=6379
spring.redis.host=localhost
spring.redis.password=123456
#redis配置连接超时,毫秒
spring.redis.timeout=2000
3.使用RedisTemplate操作Redis
package com.zyf.springTrans.redisconnection;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
public void redisOperate() {
redisTemplate.opsForValue().set("key1", "value1");
Object value1 = redisTemplate.opsForValue().get("key1");
System.out.println("key1在redis中对应的值=" + value1);
Set<Object> sts = redisTemplate.keys("*");
System.out.println(sts);
// 删除,根据key
redisTemplate.delete("key1");
// 删除,根据key组成的集合
redisTemplate.delete(sts);
}
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void stringRedisOperate() {
stringRedisTemplate.opsForValue().set("key11", "value11");
Object value11 = stringRedisTemplate.opsForValue().get("key11");
System.out.println("key11在redis中对应的值=" + value11);
Set<String> sts = stringRedisTemplate.keys("*");
System.out.println(sts);
}
}
结果发现 RedisTemplate存入的key1在Redis中的key如下:
这样不好识别,需要给RedisTemplate增加序列化器。
StringRedisTemplate操作不会有上述问题。
4.RedisTemplate增加序列化器
package com.zyf.springTrans.redisconfig;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
/**redis配置类 */
@Configuration
public class RedisConfig {
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
/** 修改RedisTemplate的序列化器:用字符串存储key,避免乱码*/
@PostConstruct // 自定义后初始化方法,在加载完bean到IoC后执行
public void initRedisSerializer() {
RedisSerializer<String> stringRedisSerializer = redisTemplate.getStringSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
}
}