Springboot集成Redis(Jedis+RedisTemplate)

川长思鸟来 2023-07-12 05:18 118阅读 0赞

talk is cheap,show you my code

源码:springboot-redis-crud

方法一:使用jedis(Jedis是Redis官方推荐的面向Java的操作Redis的客户端,详细文档可见jedis文档)

0.当然,首先你要先安装redis数据库,不会安装的自行百度(ubuntu:apt-get install redis-server)

1.创建Springboot项目

2.在pom文件中导入jedisfastjason的依赖(因为redis存储的方式为二进制存储,所以使用fastjson进行序列化)

  1. <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
  2. <dependency>
  3. <groupId>redis.clients</groupId>
  4. <artifactId>jedis</artifactId>
  5. <version>2.9.3</version>
  6. </dependency>
  7. <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
  8. <dependency>
  9. <groupId>com.alibaba</groupId>
  10. <artifactId>fastjson</artifactId>
  11. <version>1.2.50</version>
  12. </dependency>

3.在application.properties中配置redis相关参数

  1. #redis
  2. redis.host=127.0.0.1
  3. redis.port=6379
  4. redis.password=#你自己的数据库密码,默认为空
  5. redis.timeout=2000
  6. redis.poolMaxTotal=10
  7. redis.poolMaxIdle=10
  8. reids.poolMaxWait=3
  9. redis.db=0

4.创建redis包,在包下新建RedisConfig

  1. package com.wantao.jedis.redis;
  2. import lombok.Data;
  3. import org.springframework.boot.context.properties.ConfigurationProperties;
  4. import org.springframework.stereotype.Component;
  5. /** * Redis的配置类 */
  6. @Component
  7. @ConfigurationProperties(prefix = "redis")
  8. @Data
  9. public class RedisConfig {
  10. private String host;
  11. private int port;
  12. private String password;
  13. private int timeout;
  14. private int poolMaxTotal;
  15. private int poolMaxIdle;
  16. private int poolMaxWait;
  17. private int db;
  18. }

5.在包下新建RedisPoolFactory类,用来获取JedisPool对象,进而通过jedisPool.getResource()方法获得Jedis对象

  1. package com.wantao.jedis.redis;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.stereotype.Component;
  5. import redis.clients.jedis.JedisPool;
  6. import redis.clients.jedis.JedisPoolConfig;
  7. /** *创建RedisPool对象 */
  8. @Component
  9. public class RedisPoolFactory {
  10. @Autowired
  11. private RedisConfig redisConfig;
  12. @Bean
  13. public JedisPool getJedisPool(){
  14. JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
  15. jedisPoolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
  16. jedisPoolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait());
  17. jedisPoolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
  18. JedisPool jp=new JedisPool(jedisPoolConfig,redisConfig.getHost(),redisConfig.getPort(),
  19. redisConfig.getTimeout(),redisConfig.getPassword(),redisConfig.getDb());
  20. return jp;
  21. }
  22. }

6.在包下新建RedisService类,通过Jedis操纵Redis

  1. package com.wantao.jedis.redis;
  2. import com.alibaba.fastjson.JSON;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.stereotype.Service;
  6. import redis.clients.jedis.Jedis;
  7. import redis.clients.jedis.JedisPool;
  8. /** * 通过Jedis操作Redis */
  9. @Service
  10. public class RedisService {
  11. @Autowired
  12. JedisPool jedisPool;
  13. /** * 获取对象 * @param key * @param clazz * @param <T> * @return */
  14. public <T> T get(String key, Class<T> clazz) {
  15. Jedis jedis = null;
  16. try {
  17. jedis = jedisPool.getResource();
  18. String str = jedis.get(key);
  19. T t = stringToBean(str, clazz);
  20. return t;
  21. }finally {
  22. closeJedis(jedis);
  23. }
  24. }
  25. /** * 设置对象 * @param key * @param value * @param <T> * @return */
  26. public <T> boolean set(String key,T value){
  27. Jedis jedis=null;
  28. try {
  29. jedis=jedisPool.getResource();
  30. String str=beanToString(value);
  31. if (str==null||str.length()<=0){
  32. return false;
  33. }
  34. jedis.set(key,str);
  35. return true;
  36. }finally {
  37. closeJedis(jedis);
  38. }
  39. }
  40. /** * 删除 * @param key * @return */
  41. public boolean delete(String key){
  42. Jedis jedis=null;
  43. try{
  44. jedis=jedisPool.getResource();
  45. long ret=jedis.del(key);
  46. return ret>0;
  47. }finally {
  48. closeJedis(jedis);
  49. }
  50. }
  51. /** * 判断key是否存在 * @param key * @param <T> * @return */
  52. public <T> boolean exists(String key){
  53. Jedis jedis=null;
  54. try{
  55. jedis=jedisPool.getResource();
  56. return jedis.exists(key);
  57. }finally {
  58. closeJedis(jedis);
  59. }
  60. }
  61. /** * 增加值 * @param key * @param <T> * @return */
  62. public<T> Long incr(String key){
  63. Jedis jedis=null;
  64. try{
  65. jedis=jedisPool.getResource();
  66. return jedis.incr(key);
  67. }finally {
  68. closeJedis(jedis);
  69. }
  70. }
  71. /** * 减少值 * @param key * @param <T> * @return */
  72. public<T> Long decr(String key){
  73. Jedis jedis=null;
  74. try{
  75. jedis=jedisPool.getResource();
  76. return jedis.decr(key);
  77. }finally {
  78. closeJedis(jedis);
  79. }
  80. }
  81. /** * 关闭jedis * @param jedis */
  82. private void closeJedis(Jedis jedis) { //用完记得要关闭
  83. if (jedis != null) {
  84. jedis.close();
  85. }
  86. }
  87. /** * 将String转换为其他对象 * * @param str * @param clazz * @param <T> * @return */
  88. private <T> T stringToBean(String str, Class<T> clazz) {
  89. if (str == null || str.length() <= 0 || clazz == null) {
  90. return null;
  91. }
  92. if (clazz == int.class || clazz == Integer.class) {
  93. return (T) Integer.valueOf(str);
  94. } else if (clazz == String.class) {
  95. return (T) str;
  96. } else if (clazz == long.class || clazz == Long.class) {
  97. return (T) Long.valueOf(str);
  98. } else {
  99. return JSON.toJavaObject(JSON.parseObject(str), clazz);
  100. }
  101. }
  102. /** * 将其他对象转换为String * @param value * @param <T> * @return */
  103. private <T> String beanToString(T value) {
  104. if (value == null) {
  105. return null;
  106. }
  107. Class<?> clazz = value.getClass();
  108. if (clazz == int.class || clazz == Integer.class) {
  109. return "" + value;
  110. } else if (clazz == String.class) {
  111. return (String) value;
  112. } else if (clazz == long.class || clazz == Long.class) {
  113. return "" + value;
  114. } else {
  115. return JSON.toJSONString(value);
  116. }
  117. }
  118. }

7.建立result包,新建Result类,将返回的json封装,更好的展示

  1. package com.wantao.jedis.result;
  2. import lombok.Data;
  3. import lombok.NoArgsConstructor;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. /** * 返回的Json数据封装 */
  7. @Data
  8. @NoArgsConstructor
  9. public class Result{
  10. private Integer code;
  11. private String msg;
  12. private Map<String, Object> data = new HashMap<String, Object>();
  13. /** * 成功时调用 * 默认状态码:200 */
  14. public static Result success() {
  15. Result result = new Result();
  16. result.setCode(200);
  17. result.setMsg("处理成功");
  18. return result;
  19. }
  20. /** * 失败时调用 * 默认状态码:500 */
  21. public static Result error() {
  22. Result result = new Result();
  23. result.setCode(500);
  24. result.setMsg("处理失败");
  25. return result;
  26. }
  27. /** * 设置数据 * @param key * @param value * @return */
  28. public Result add(String key,Object value){
  29. this.data.put(key,value);
  30. return this;
  31. }
  32. }

8.创建controller包,新建JedisController类(这里就只调用get,set方法进行测试)

  1. package com.wantao.jedis.controller;
  2. import com.wantao.jedis.redis.RedisService;
  3. import com.wantao.jedis.result.Result;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. @Controller
  9. public class JedisController {
  10. @Autowired
  11. private RedisService redisService;
  12. @GetMapping("/set")
  13. @ResponseBody
  14. public Result set(){
  15. redisService.set("girlfriend","sakura");
  16. return Result.success();
  17. }
  18. @GetMapping("/get")
  19. @ResponseBody
  20. public Result get(){
  21. String str=redisService.get("girlfriend",String.class);
  22. return Result.success().add("girlfriend",str);
  23. }
  24. }

结果截图:
set:
set
get:
get
查看redis数据库,看是否将数据插入:
在这里插入图片描述
方法二:使用RedisTemplate
(RedisTemplate是SpringDataRedis中对JedisApi的高度封装。
SpringDataRedis相对于Jedis来说可以方便地更换Redis的Java客户端,比Jedis多了自动管理连接池的特性,方便与其他Spring框架进行搭配使用如:SpringCache)

1.创建springboot项目

2.在pom文件中导入spring-boot-starter-data-redis依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>

3.在application.properties中配置redis相关的属性

  1. #redis
  2. spring.redis.host=127.0.0.1
  3. spring.redis.port=6379
  4. spring.redis.password=#你自己的redis密码,默认为空
  5. spring.redis.timeout=2000
  6. spring.redis.jedis.pool.max-active=10
  7. spring.redis.jedis.pool.max-idle=10
  8. spring.redis.jedis.pool.max-wait=3
  9. spring.redis.database=0

4创建redis包,新建RedisUtil类,用来创建RedisTemplate或者StringRedisTemplate对象(RedisTemplate和StringRedisTemplate的区别)

  1. package com.wantao.redistemplate.redis;
  2. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  3. import com.fasterxml.jackson.annotation.PropertyAccessor;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.data.redis.connection.RedisConnectionFactory;
  8. import org.springframework.data.redis.core.RedisTemplate;
  9. import org.springframework.data.redis.core.StringRedisTemplate;
  10. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  11. import org.springframework.data.redis.serializer.StringRedisSerializer;
  12. /** * StringRedisTemplate与RedisTemplate区别点 * 两者的关系是StringRedisTemplate继承RedisTemplate。 * * 两者的数据是不共通的;也就是说StringRedisTemplate只能管理StringRedisTemplate里面的数据,RedisTemplate只能管理RedisTemplate中的数据。 * * 其实他们两者之间的区别主要在于他们使用的序列化类: *     RedisTemplate使用的是JdkSerializationRedisSerializer 存入数据会将数据先序列化成字节数组然后在存入Redis数据库。 * *      StringRedisTemplate使用的是StringRedisSerializer * * 使用时注意事项: *    当你的redis数据库里面本来存的是字符串数据或者你要存取的数据就是字符串类型数据的时候,那么你就使用StringRedisTemplate即可。 *    但是如果你的数据是复杂的对象类型,而取出的时候又不想做任何的数据转换,直接从Redis里面取出一个对象,那么使用RedisTemplate是更好的选择。 */
  13. @Configuration
  14. public class RedisUtil {
  15. //两种reidsTemplate根据场景自由选择
  16. @Bean
  17. public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
  18. RedisTemplate<Object, Object> template = new RedisTemplate<>();
  19. template.setConnectionFactory(connectionFactory);
  20. //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
  21. Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
  22. ObjectMapper mapper = new ObjectMapper();
  23. mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  24. mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  25. serializer.setObjectMapper(mapper);
  26. template.setValueSerializer(serializer);
  27. //使用StringRedisSerializer来序列化和反序列化redis的key值
  28. template.setKeySerializer(new StringRedisSerializer());
  29. template.afterPropertiesSet();
  30. return template;
  31. }
  32. @Bean
  33. public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
  34. StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
  35. stringRedisTemplate.setConnectionFactory(factory);
  36. return stringRedisTemplate;
  37. }
  38. }

5.建立result包,新建Result类,将返回的json封装,更好的展示

  1. package com.wantao.redistemplate.result;
  2. import lombok.Data;
  3. import lombok.NoArgsConstructor;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. /** * 返回的Json数据封装 */
  7. @Data
  8. @NoArgsConstructor
  9. public class Result {
  10. private Integer code;
  11. private String msg;
  12. private Map<String, Object> data = new HashMap<String, Object>();
  13. /** * 成功时调用 * 默认状态码:200 */
  14. public static Result success() {
  15. Result result = new Result();
  16. result.setCode(200);
  17. result.setMsg("处理成功");
  18. return result;
  19. }
  20. /** * 失败时调用 * 默认状态码:500 */
  21. public static Result error() {
  22. Result result = new Result();
  23. result.setCode(500);
  24. result.setMsg("处理失败");
  25. return result;
  26. }
  27. /** * 设置数据 * @param key * @param value * @return */
  28. public Result add(String key,Object value){
  29. this.data.put(key,value);
  30. return this;
  31. }
  32. }

6.创建controller包,新建redisTemplateController,进行getset方法测试

  1. package com.wantao.redistemplate.controller;
  2. import com.wantao.redistemplate.redis.RedisService;
  3. import com.wantao.redistemplate.result.Result;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. @Controller
  9. public class redisTemplateController {
  10. @Autowired
  11. private RedisService redisService;
  12. @GetMapping("/set")
  13. @ResponseBody
  14. public Result set(){
  15. redisService.set("boyfriend","selenium");
  16. return Result.success();
  17. }
  18. @GetMapping("/get")
  19. @ResponseBody
  20. public Result get(){
  21. String str=redisService.get("boyfriend");
  22. return Result.success().add("boyfriend",str);
  23. }
  24. }

测试截图:

set:
在这里插入图片描述

get:
在这里插入图片描述
在redis中查看:
在这里插入图片描述

源码:springboot-redis-crud

发表评论

表情:
评论列表 (有 0 条评论,118人围观)

还没有评论,来说两句吧...

相关阅读