继续以前的系列,这节咱们来撸 springboot 框架中如何使用 redishtml
引入序列化依赖,咱们是想把上一个项目中从数据库获取到的实体,序列化到 Redis 中java
注意:我这里是集群配置,固然你也能够配置单点的也没有问题web
附代码:redis
package com.ncat.webdemo.controller;
import com.ncat.webdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ncat.webdemo.pojo.User;
import java.time.Duration;
@RestController
@RequestMapping(value = {"user"})
public class UserController {
@Autowired
private UserService userService;
@Autowired
RedisTemplate redisTemplate;
@RequestMapping(value = {"test"})
public User Test(@RequestParam Integer id) {
String redisKey = "Test:User:" + id;
// key序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
//val实例化
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
ValueOperations<String, User> operations = redisTemplate.opsForValue();
if (redisTemplate.hasKey(redisKey)) {
return operations.get(redisKey);
} else {
User user = userService.selectByPrimaryKey(id);
operations.set(redisKey, user, Duration.ofSeconds(300));
return user;
}
}
}
分析错误,应该是咱们的实体 User 不能序列化致使spring
成功了,咱们查看下 Redissql
也能够查到了数据库