引入组件
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
|
添加配置
1 2 3 4 5 6 7 8 9 10 11 12 13
| spring: redis: database: 0 host: 127.0.0.1 port: 6379 password: timeout: 5000 jedis: pool: max-active: 8 max-wait: -1 max-idle: 8 min-idle: 0
|
添加测试接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| package com.example;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.data.redis.core.StringRedisTemplate; import java.util.HashMap; import java.util.Map;
@RestController @RequestMapping("/api/redis") public class DebugRedis { @Autowired private StringRedisTemplate stringRedisTemplate; @RequestMapping("/set") public Map<String, Object> function(String key, String value) { this.stringRedisTemplate.opsForValue().set(key, value); Map<String, Object> result = new HashMap<>(); result.put("code", 0); result.put("message", "success"); result.put("exec_result", 1); return result; }
@RequestMapping("/get") public Map<String, Object> function(String key) { Map<String, Object> result = new HashMap<>(); result.put("code", 0); result.put("message", "success"); result.put("exec_result", this.stringRedisTemplate.opsForValue().get(key)); return result; } }
|
测试
设置key: /api/redis/set?key=name&value=spring-boot
读取key: /api/redis/get?key=name