繼續以前的系列,這節咱們來擼 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
也能夠查到了數據庫