Java 实战 spingboot-redis

继续之前的系列,这节我们来撸 springboot 框架中如何使用 redis

 

pom.xml 文件中 引入 redis 的依赖,引入 序列化的 依赖

  引入序列化依赖,我们是想把上一个项目中从数据库获取到的实体,序列化到 Redis 中

 

 

 

application.yml 文件中,对 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 不能序列化导致

让 实体 User 实现 Serializable

 

 

 再次运行

 

 

 成功了,我们查看下 Redis

 

 

 也可以查到了

 

 

系列文章

posted @ 2019-09-04 13:43  NCat  阅读(390)  评论(0编辑  收藏  举报