介绍
StringRedisTemplate 只支持 redis 中 string 类型的操作,其他类型不支持
可直接使用 StringRedisTemplate
因为在 RedisAutoConfiguration 类中已经配置了 StringRedisTemplate,如下:
public class RedisAutoConfiguration {
public RedisAutoConfiguration() {
}
@Bean
@ConditionalOnMissingBean(
name = {"redisTemplate"}
)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
创建springboot工程
见:https://www.malaoshi.top/show_1EF5qXjMmlZR.html
添加依赖
修改pom.xml
<!--springboot中的redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
添加配置文件
在 resources 目录下创建 application.yml 文件
配置redis连接
spring:
redis:
host: localhost
port: 6379
password:
timeout: 1000 # 连接超时时间(毫秒)
database: 0 # Redis数据库索引(默认为0)
jedis:
pool:
max-wait: 30000
max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
max-idle: 8 # 连接池中的最大空闲连接
min-idle: 2 # 连接池中的最小空闲连接
Controller
@RestController
@RequestMapping("/string")
public class TestStringCtrl {
@Resource
private StringRedisTemplate template;
@RequestMapping("/set")
public void set(){
template.boundValueOps("123_like").set("0");
}
@RequestMapping("/incr")
public Long incr(){
return template.boundValueOps("123_like").increment();
}
@RequestMapping("/decr")
public Long decr(){
return template.boundValueOps("123_like").decrement();
}
@RequestMapping("/get")
public String get(){
return template.boundValueOps("123_like").get();
}
}
测试
访问 http://localhost:8080/string/set ,添加数据
访问 http://localhost:8080/string/get ,获取数据
访问 http://localhost:8080/string/incr ,增加1
访问 http://localhost:8080/string/decr ,减少1