SpringBoot通过Jedis整合Redis

淡淡的烟草味﹌ 2023-06-16 15:58 53阅读 0赞

1.pom.xml添加Jedis依赖

  1. <dependency>
  2. <groupId>redis.clients</groupId>
  3. <artifactId>jedis</artifactId>
  4. </dependency>

2.application.properties添加Redis配置

  1. # Redis服务器地址
  2. spring.redis.host=127.0.0.1
  3. # Redis服务器连接端口
  4. spring.redis.port=6379
  5. # Redis服务器连接密码
  6. spring.redis.password=123456
  7. # 连接超时时间(毫秒)
  8. spring.redis.timeout=10000
  9. # 连接池最大连接数(使用负值表示没有限制)
  10. spring.redis.pool.max-active=1000
  11. # 连接池中的最大空闲连接
  12. spring.redis.pool.max-idle=500
  13. # 连接池中的最小空闲连接
  14. spring.redis.pool.min-idle=0
  15. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  16. spring.redis.pool.max-wait=10000

3.注入JedisPool实例

  1. import org.springframework.beans.factory.annotation.Value;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import redis.clients.jedis.JedisPool;
  5. import redis.clients.jedis.JedisPoolConfig;
  6. @Configuration
  7. public class RedisPoolFactory {
  8. @Value("${spring.redis.host}")
  9. private String host;
  10. @Value("${spring.redis.port}")
  11. private int port;
  12. @Value("${spring.redis.password}")
  13. private String password;
  14. @Value("${spring.redis.timeout}")
  15. private int timeout;
  16. @Value("${spring.redis.pool.max-active}")
  17. private int maxActive;
  18. @Value("${spring.redis.pool.max-idle}")
  19. private int maxIdle;
  20. @Value("${spring.redis.pool.min-idle}")
  21. private int minIdle;
  22. @Value("${spring.redis.pool.max-wait}")
  23. private long maxWaitMillis;
  24. //JedisPool的实例注入到spring容器里面
  25. @Bean
  26. public JedisPool JedisPoolFactory() {
  27. JedisPoolConfig poolConfig = new JedisPoolConfig();
  28. poolConfig.setMaxTotal(maxActive);
  29. poolConfig.setMaxIdle(maxIdle);
  30. poolConfig.setMinIdle(minIdle);
  31. poolConfig.setMaxWaitMillis(maxWaitMillis);
  32. JedisPool jedisPool = new JedisPool(poolConfig,host,port,timeout,password);
  33. return jedisPool;
  34. }
  35. }

4.创建Redis业务操作类

  1. import java.util.List;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Service;
  4. import com.alibaba.fastjson.JSON;
  5. import com.alibaba.fastjson.JSONArray;
  6. import redis.clients.jedis.Jedis;
  7. import redis.clients.jedis.JedisPool;
  8. @Service
  9. public class RedisService {
  10. @Autowired
  11. private JedisPool jedisPool;
  12. /**
  13. * 获取对象
  14. */
  15. public <T> T get(String key,Class<T> clazz){
  16. Jedis jedis = null;
  17. try {
  18. jedis = jedisPool.getResource();
  19. String str = jedis.get(key);
  20. //将String转换为Bean
  21. T t = stringToBean(str,clazz);
  22. return t;
  23. }finally {
  24. if(jedis != null) {
  25. jedis.close();
  26. }
  27. }
  28. }
  29. /**
  30. * 设置对象
  31. */
  32. public <T> boolean set(String key,T value){
  33. Jedis jedis = null;
  34. try {
  35. jedis = jedisPool.getResource();
  36. //将Bean转换为String
  37. String str = beanToString(value);
  38. if(str == null || str.length() <= 0) {
  39. return false;
  40. }
  41. jedis.set(key, str);
  42. return true;
  43. }finally {
  44. if(jedis != null) {
  45. jedis.close();
  46. }
  47. }
  48. }
  49. /**
  50. * 设置对象,含过期时间(单位:秒)
  51. */
  52. public <T> boolean set(String key,T value,int expireTime){
  53. Jedis jedis = null;
  54. try {
  55. jedis = jedisPool.getResource();
  56. //将Bean转换为String
  57. String str = beanToString(value);
  58. if(str == null || str.length() <= 0) {
  59. return false;
  60. }
  61. if(expireTime <= 0) {
  62. //有效期:代表不过期
  63. jedis.set(key, str);
  64. }else {
  65. jedis.setex(key, expireTime, str);
  66. }
  67. return true;
  68. }finally {
  69. if(jedis != null) {
  70. jedis.close();
  71. }
  72. }
  73. }
  74. /**
  75. * 减少值
  76. */
  77. public <T> Long decr(String key){
  78. Jedis jedis = null;
  79. try {
  80. jedis = jedisPool.getResource();
  81. //返回value减1后的值
  82. return jedis.decr(key);
  83. }finally {
  84. if(jedis != null) {
  85. jedis.close();
  86. }
  87. }
  88. }
  89. /**
  90. * 增加值
  91. */
  92. public <T> Long incr(String key){
  93. Jedis jedis = null;
  94. try {
  95. jedis = jedisPool.getResource();
  96. //返回value加1后的值
  97. return jedis.incr(key);
  98. }finally {
  99. if(jedis != null) {
  100. jedis.close();
  101. }
  102. }
  103. }
  104. /**
  105. * 删除对象
  106. */
  107. public boolean delete(String key){
  108. Jedis jedis = null;
  109. try {
  110. jedis = jedisPool.getResource();
  111. long ret = jedis.del(key);
  112. return ret > 0;//删除成功,返回大于0
  113. }finally {
  114. if(jedis != null) {
  115. jedis.close();
  116. }
  117. }
  118. }
  119. /**
  120. * 检查key是否存在
  121. */
  122. public <T> boolean exitsKey(String key){
  123. Jedis jedis = null;
  124. try {
  125. jedis = jedisPool.getResource();
  126. return jedis.exists(key);
  127. }finally {
  128. if(jedis != null) {
  129. jedis.close();
  130. }
  131. }
  132. }
  133. /**
  134. * 将字符串转换为Bean对象
  135. */
  136. @SuppressWarnings("unchecked")
  137. public static <T> T stringToBean(String str,Class<T> clazz) {
  138. if(str == null || str.length() == 0 || clazz == null) {
  139. return null;
  140. }
  141. if(clazz == int.class || clazz == Integer.class) {
  142. return ((T) Integer.valueOf(str));
  143. }else if(clazz == String.class) {
  144. return (T) str;
  145. }else if(clazz == long.class || clazz == Long.class) {
  146. return (T) Long.valueOf(str);
  147. }else if(clazz == List.class) {
  148. return JSON.toJavaObject(JSONArray.parseArray(str), clazz);
  149. }else {
  150. return JSON.toJavaObject(JSON.parseObject(str), clazz);
  151. }
  152. }
  153. /**
  154. * 将Bean对象转换为字符串类型
  155. */
  156. public static <T> String beanToString(T value) {
  157. if(value == null){
  158. return null;
  159. }
  160. Class<?> clazz = value.getClass();
  161. if(clazz == int.class || clazz == Integer.class) {
  162. return ""+value;
  163. }else if(clazz == String.class) {
  164. return (String)value;
  165. }else if(clazz == long.class || clazz == Long.class) {
  166. return ""+value;
  167. }else {
  168. return JSON.toJSONString(value);
  169. }
  170. }
  171. }

5.测试缓存

  1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3. import java.util.List;
  4. import java.util.Map;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. import cn.com.app.redis.RedisService;
  10. @Controller
  11. public class Test {
  12. @Autowired
  13. private RedisService redisService;
  14. @RequestMapping("/test")
  15. @ResponseBody
  16. public void test() throws Exception {
  17. //普通类型
  18. redisService.set("key1", "hello");
  19. String str = redisService.get("key1",String.class);
  20. System.out.println("读取缓存普通类型:"+str);
  21. //Map集合
  22. Map<String,Object> map = new HashMap<>();
  23. map.put("name", "aaa");
  24. redisService.set("map", map);
  25. Map<String,Object> resultMap = redisService.get("map",Map.class);
  26. System.out.println("读取缓存Map类型:"+resultMap);
  27. //List集合
  28. List<Object> list = new ArrayList<>();
  29. Map<String,Object> map1 = new HashMap<>();
  30. map1.put("name", "bbb");
  31. list.add(map);
  32. list.add(map1);
  33. redisService.set("list", list);
  34. List<Map<String,Object>> resultList = redisService.get("list",List.class);
  35. System.out.println("读取缓存List类型全部元素:"+resultList);
  36. }
  37. }

发表评论

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

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

相关阅读

    相关 SpringBoot整合Jedis

    文章目录 Jedis操作String类型 Jedis操作Hash类型 我们在使用springboot搭建微服务的时候,在很多时候还是需要redis的高