开发环境搭建
docker run -d --name redis -p 6379:6379 redis:4.0

依赖配置
maven
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
配置 Redis
# redis config#redis机器ipspring.redis.host=127.0.0.1#redis端口spring.redis.port=6379#redis密码spring.redis.password=#目标数据库序号spring.redis.database=1#redis超时时间(毫秒),如果不设置,取默认值2000spring.redis.timeout=10000ms#连接池的最大数据库连接数。spring.redis.jedis.pool.max-active=300#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。spring.redis.jedis.pool.max-wait=1000ms
HelloWorld
测试代码
import cn.bx.springbootup.model.CacheValReq;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;@RestControllerpublic class RedisController {@Resourceprivate StringRedisTemplate stringRedisTemplate;@PostMapping("/addCacheVal")public Boolean addCacheVal(@RequestBody CacheValReq req) {try {stringRedisTemplate.opsForValue().set(req.getKey(), req.getVal());} catch (Exception e) {e.printStackTrace();return false;}return true;}@GetMapping("/getCacheVal")public String getCacheVal(@RequestParam String key) {return stringRedisTemplate.opsForValue().get(key);}}
其中对请求参数CacheValReq的类如下
public class CacheValReq {private String key;private String val;public String getKey() {return key;}public String getVal() {return val;}}
测试 添加数据
curl --location --request POST 'localhost:8080/addCacheVal' \--header 'Content-Type: application/json' \--data-raw '{"key": "k1","val": "v1"}'
测试获取数据
curl --location --request GET 'localhost:8080/getCacheVal?key=k1'
