首先在pom.xml中引入maven依赖
<!-- 引入 redis 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
修改application.yml的配置信息
spring: redis: database: 1 #数据库索引(默认为0) host: 47.98.171.29 #服务器地址 port: 6379 #服务器连接端口 password: 12345678 # Redis服务器连接密码(默认为空) pool: max-active: 100 # 连接池最大连接数(使用负值表示没有限制) 默认8 max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认-1 max-idle: 10 # 连接池中的最大空闲连接 默认8 min-idle: 1 # 连接池中的最小空闲连接 默认0 timeout: 0 # 连接超时时间(毫秒)
在控制器中注入StringRedisTemplate,使用set和get方法。如下:
@Autowired private StringRedisTemplate stringRedisTemplate; @RequestMapping(value = "store") public void redisStore(){ String a = stringRedisTemplate.opsForValue().get("a"); int value = Integer.valueOf(a)+1; stringRedisTemplate.opsForValue().set("a",String.valueOf(value)); }