1 ,在pom文件中引入
org.springframework.boot
spring-boot-starter-data-redis
2,配置文件
spring:
redis:
# Redis数据库索引(默认为0)
database: 0
host: localhost
password:
port: 6379
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池中的最大空闲连接
max-idle: 20
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
# 连接池中的最小空闲连接
min-idle: 0
# 连接超时时间(毫秒)
timeout: 0
3 config java 类
@Configuration
public class RedisConfig {
@Autowired
private RedisConnectionFactoryredisConnectionFactory;
@Bean
public RedisTemplatefunctionDomainRedisTemplate() {
RedisTemplate redisTemplate =new RedisTemplate<>();
initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
return redisTemplate;
}
private void initDomainRedisTemplate(RedisTemplate redisTemplate, RedisConnectionFactory factory) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new EntityRedisSerializer());
redisTemplate.setValueSerializer(new EntityRedisSerializer());
redisTemplate.setConnectionFactory(factory);
}
/**
* 实例化HashOperations对象
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperationshashOperations(RedisTemplate redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 实例化ListOperations对象
* @param redisTemplate
* @return
*/
@Bean
public ListOperationslistOperations(RedisTemplate redisTemplate){
return redisTemplate.opsForList();
}
}
public class EntityRedisSerializerimplements RedisSerializer {
@Override
public byte[]serialize(Object o)throws SerializationException {
if(o ==null){
return new byte[0];
}
return SerializerUtil.serialize(o);
}
@Override
public Objectdeserialize(byte[] bytes)throws SerializationException {
if(bytes ==null || bytes.length ==0){
return null;
}
return SerializerUtil.unserialize(bytes);
}
}
public class SerializerUtil {
public static byte[]serialize(Object object){
ObjectOutputStream oos =null;
ByteArrayOutputStream baos =null;
try {
baos =new ByteArrayOutputStream();
oos =new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static Objectunserialize(byte[] bytes){
ByteArrayInputStream bais =null;
try {
bais =new ByteArrayInputStream(bytes);
ObjectInputStream ois =new ObjectInputStream(bais);
return ois.readObject();
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
4 在业务代码中使用
@Autowired
private RedisTemplateredisTemplate;
@Resource(name ="redisTemplate")
ValueOperationsvalueOperations;
valueOperations.set(key,value);