初始项目
pom.xml引入redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
properties中添加redis配置
这里只做简单配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
在开始写代码之前,请先确保本机安装了redis,并成功启动
代码编写
controller
@RestController
public class RedisCtronller {
@Autowired
private RedisTemplate<String,String> redisTemplate;
@PostMapping("/put")
public String putKey(String key,String value){
redisTemplate.opsForValue().set(key,value);
return "存入数据完成";
}
@GetMapping("/get")
public String getKey(String key){
Object value = redisTemplate.opsForValue().get(key);
String result = "";
if(value != null){
result = value.toString();
}
return result;
}
}
编写完成,则可以直接进行接口测试
先进行key值存储的测试
然后在redis-cli里面获取一次这个key
能获取到就代表成功了
接着用代码获取一次这个value
也能根据Key获取到这个值