spring boot 集成 redis
引pom文件 redis用的包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
创建一个Configuration类
@Configuration
public class RedisConfiguration {
@Bean
@ConditionalOnMissingBean(name="redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException{
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException{
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
配置yml文件
spring:
#redis
redis:
enabled: true
database: 0
host: 192.168.106.18
port: 6379
password: # 密码(默认为空)
timeout: 6000 # 连接超时时长(毫秒)
pool:
max-active: 1000 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 10 # 连接池中的最大空闲连接
min-idle: 5 # 连接池中的最小空闲连接
注入redis类
@Autowired
private StringRedisTemplate template;
测试redis add和get
public void setKey(String key,String value){
ValueOperations<String, String> ops = template.opsForValue();
ops.set(key,value);
}
public String getValue(String key){
ValueOperations<String, String> ops = this.template.opsForValue();
return ops.get(key);
}
集成完成