SpringBoot集成redis【Jedis】

布满荆棘的人生 2023-05-30 06:09 55阅读 0赞

1、pom.xml的引用

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. <version>1.18.10</version>
  5. <scope>provided</scope>
  6. </dependency>
  7. <dependency>
  8. <groupId>redis.clients</groupId>
  9. <artifactId>jedis</artifactId>
  10. <version>2.9.0</version>
  11. </dependency>
  12. <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
  13. <dependenc>
  14. <groupId>com.fasterxml.jackson.core</groupId>
  15. <artifactId>jackson-databind</artifactId>
  16. <version>2.10.0</version>
  17. </dependency>

这里的lombok是为了简化实体类的get/set

2、application.properties

  1. spring.redis.host=127.0.0.0
  2. spring.redis.port=6379
  3. spring.redis.password=
  4. #连接超时时间
  5. spring.redis.timeout=0
  6. #连接的库
  7. spring.redis.database=15
  8. #连接池配置
  9. spring.redis.pool.max-total=100
  10. spring.redis.pool.max-wait=-1
  11. spring.redis.pool.max-idle=8
  12. spring.redis.pool.min-idle=0

3、redis自动注入配置相关的信息

  1. package com.cat.code.config;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import redis.clients.jedis.JedisPool;
  6. import redis.clients.jedis.JedisPoolConfig;
  7. @Configuration
  8. public class JedisConf {
  9. @Value("${spring.redis.host}")
  10. private String redisHost;
  11. @Value("${spring.redis.port}")
  12. private int redisPort;
  13. @Value("${spring.redis.password}")
  14. private String redisPasswd;
  15. @Value("${spring.redis.database}")
  16. private int redisDb;
  17. @Value("${spring.redis.timeout}")
  18. private int redisTimeout;
  19. @Value("${spring.redis.pool.max-total}")
  20. private int redisMaxTotal;
  21. @Value("${spring.redis.pool.max-wait}")
  22. private int redisMaxWait;
  23. @Value("${spring.redis.pool.max-idle}")
  24. private int redisMaxIdle;
  25. @Value("${spring.redis.pool.min-idle}")
  26. private int redisMinIdle;
  27. @Bean
  28. public JedisPool redisPoolFactory() throws Exception{
  29. JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
  30. jedisPoolConfig.setMaxTotal(redisMaxTotal);
  31. jedisPoolConfig.setMaxIdle(redisMaxIdle);
  32. jedisPoolConfig.setMinIdle(redisMinIdle);
  33. jedisPoolConfig.setMaxWaitMillis(redisMaxWait);
  34. jedisPoolConfig.setTestOnBorrow(true);
  35. jedisPoolConfig.setTestOnReturn(true);
  36. // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
  37. // jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
  38. // 是否启用pool的jmx管理功能, 默认true
  39. jedisPoolConfig.setJmxEnabled(true);
  40. if (redisPasswd != null && redisPasswd.trim().length() == 0) {
  41. redisPasswd = null;
  42. }
  43. JedisPool jedisPool = new JedisPool(jedisPoolConfig, redisHost, redisPort, redisTimeout, redisPasswd, redisDb);
  44. return jedisPool;
  45. }
  46. }

4、对jedis调用进行简单封装,每次重新获取连接池资源和归还连接池资源

  1. package com.cat.code.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Component;
  4. import redis.clients.jedis.Jedis;
  5. import redis.clients.jedis.JedisPool;
  6. import java.io.Serializable;
  7. import java.util.Set;
  8. /**
  9. * @Description: 配置redis连接池
  10. */
  11. @Component
  12. public class RedisTemplate {
  13. @Autowired
  14. private JedisPool jedisPool;
  15. /**
  16. * key-value存储
  17. * @param key
  18. * @param value
  19. * @return
  20. */
  21. public boolean set(String key, String value) {
  22. Jedis jedis = null;
  23. try {
  24. jedis = jedisPool.getResource();
  25. String res = jedis.set(key, value);
  26. return (res == null || !res.equalsIgnoreCase("OK") ? false : true);
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. } finally {
  30. if (jedis != null) {
  31. jedis.close();
  32. }
  33. }
  34. return false;
  35. }
  36. /**
  37. * key-value存储设置过期时间
  38. * @param key
  39. * @param value
  40. * @param expire_time
  41. * @return
  42. */
  43. public boolean set(String key, String value, int expire_time) {
  44. Jedis jedis = null;
  45. try {
  46. jedis = jedisPool.getResource();
  47. String res = jedis.set(key, value, "NX", "EX", expire_time);
  48. return (res == null || !res.equalsIgnoreCase("OK") ? false : true);
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. } finally {
  52. if (jedis != null) {
  53. jedis.close();
  54. }
  55. }
  56. return false;
  57. }
  58. /**
  59. * key-value存储设置过期时间,当存在替换为新的值
  60. * @param key
  61. * @param value
  62. * @param expire_time
  63. * @return
  64. */
  65. public boolean setex(String key, String value, int expire_time) {
  66. Jedis jedis = null;
  67. try {
  68. jedis = jedisPool.getResource();
  69. String res = jedis.setex(key, expire_time, value);
  70. return (res == null || !res.equalsIgnoreCase("OK") ? false : true);
  71. } catch (Exception e) {
  72. e.printStackTrace();
  73. } finally {
  74. if (jedis != null) {
  75. jedis.close();
  76. }
  77. }
  78. return false;
  79. }
  80. /**
  81. * 获取key-value 值
  82. * @param key
  83. * @return
  84. */
  85. public String get(String key) {
  86. Jedis jedis = null;
  87. try {
  88. jedis = jedisPool.getResource();
  89. String res = jedis.get(key);
  90. return res;
  91. } catch (Exception e) {
  92. e.printStackTrace();
  93. } finally {
  94. if (jedis != null) {
  95. jedis.close();
  96. }
  97. }
  98. return null;
  99. }
  100. /**
  101. * key是否存在
  102. * @param key
  103. * @return
  104. */
  105. public boolean exist(String key) {
  106. Jedis jedis = null;
  107. try {
  108. jedis = jedisPool.getResource();
  109. Boolean res = jedis.exists(key);
  110. return res;
  111. } catch (Exception e) {
  112. e.printStackTrace();
  113. } finally {
  114. if (jedis != null) {
  115. jedis.close();
  116. }
  117. }
  118. return false;
  119. }
  120. /**
  121. * list左进队列
  122. * @param key
  123. * @param values
  124. * @return
  125. */
  126. public Long lpush(String key, String... values) {
  127. Jedis jedis = null;
  128. try {
  129. jedis = jedisPool.getResource();
  130. Long ret = jedis.lpush(key, values);
  131. return ret;
  132. } catch (Exception e) {
  133. e.printStackTrace();
  134. } finally {
  135. if (jedis != null) {
  136. jedis.close();
  137. }
  138. }
  139. return null;
  140. }
  141. /**
  142. * list 右进队列
  143. * @param key
  144. * @return
  145. */
  146. public String rpop(String key) {
  147. Jedis jedis = null;
  148. try {
  149. jedis = jedisPool.getResource();
  150. String value = jedis.rpop(key);
  151. return value;
  152. } catch (Exception e) {
  153. e.printStackTrace();
  154. } finally {
  155. if (jedis != null) {
  156. jedis.close();
  157. }
  158. }
  159. return null;
  160. }
  161. /**
  162. * set key-values存储
  163. * @param key
  164. * @param values
  165. * @return
  166. */
  167. public Long sadd(String key,String... values){
  168. Jedis jedis = null;
  169. try {
  170. jedis = jedisPool.getResource();
  171. return jedis.sadd(key,values);
  172. } catch (Exception e) {
  173. System.err.println(e.getMessage());
  174. return null;
  175. } finally {
  176. if (jedis != null) {
  177. jedis.close();
  178. }
  179. }
  180. }
  181. /**
  182. * set key-value获取
  183. * @param key
  184. * @return
  185. */
  186. public String spop(String key){
  187. Jedis jedis = null;
  188. try {
  189. jedis = jedisPool.getResource();
  190. return jedis.spop(key);
  191. } catch (Exception e) {
  192. System.err.println(e.getMessage());
  193. return null;
  194. } finally {
  195. if (jedis != null) {
  196. jedis.close();
  197. }
  198. }
  199. }
  200. /**
  201. *命令将 key 中储存的数字值增一
  202. * @param key
  203. * @return
  204. */
  205. public Long incr(String key){
  206. Jedis jedis = null;
  207. try {
  208. jedis = jedisPool.getResource();
  209. return jedis.incr(key);
  210. } catch (Exception e) {
  211. System.err.println(e.getMessage());
  212. return null;
  213. } finally {
  214. if (jedis != null) {
  215. jedis.close();
  216. }
  217. }
  218. }
  219. }

5、User实体类,继承Serializable序列化是非必要

  1. package com.cat.code.po;
  2. import lombok.Data;
  3. import java.io.Serializable;
  4. /**
  5. * @Author: lvgang
  6. * @Time: 2019/10/29 16:43
  7. * @Email: lvgang@golaxy.cn
  8. * @Description: todo
  9. */
  10. @Data
  11. public class User implements Serializable {
  12. private static final long serialVersionUID = 1L;
  13. private Long id;
  14. private String name;
  15. private Integer age;
  16. public User(){}
  17. public User(Long id,String name,Integer age){
  18. this.id = id;
  19. this.name = name;
  20. this.age = age;
  21. }
  22. }

6、调用redis存取,在大部分情况下是OK的,保证资源存取不会出现问题

  1. package com.cat.code;
  2. import com.cat.code.config.RedisTemplate;
  3. import com.cat.code.po.User;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.boot.test.context.SpringBootTest;
  11. import org.springframework.test.context.junit4.SpringRunner;
  12. import java.util.concurrent.ExecutorService;
  13. import java.util.concurrent.Executors;
  14. import java.util.stream.IntStream;
  15. /**
  16. * @Author: lvgang
  17. * @Time: 2019/10/29 17:05
  18. * @Email: lvgang@golaxy.cn
  19. * @Description: todo
  20. */
  21. @RunWith(SpringRunner.class)
  22. @SpringBootTest(classes = ServiceSpringDataRedisApplication.class)
  23. public class RedisTest {
  24. private Logger logger = LoggerFactory.getLogger(RedisTest.class);
  25. @Autowired
  26. private RedisTemplate redisTemplate;
  27. @Autowired
  28. private ObjectMapper objectMapper = new ObjectMapper();
  29. @Test
  30. public void test1() throws Exception{
  31. String key = "user1";
  32. String json = objectMapper.writeValueAsString(new User(1L,"admin",21));
  33. redisTemplate.set(key,json);
  34. String value = redisTemplate.get(key);
  35. User user = objectMapper.readValue(value,User.class);
  36. logger.info("user:{}",user.toString());
  37. }
  38. @Test
  39. public void test2(){
  40. ExecutorService executorService = Executors.newFixedThreadPool(1000);
  41. IntStream.range(0, 1000).forEach(i->{
  42. executorService.execute(()->{
  43. logger.info("i:{}",i);
  44. redisTemplate.incr("count");//累加
  45. if(i%2==1){
  46. redisTemplate.sadd("set",""+i);//添加
  47. }else {
  48. String value = redisTemplate.spop("set");//取出
  49. logger.info("第i次:{}获取{}",i,value);
  50. }
  51. });
  52. });
  53. }
  54. }

7、写在最后,当我们对redis连接要求不是那么高时,我建议直接使用spring-boot-data-redis

  1. pom.xml依赖
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. <version>2.1.8.RELEASE</version>
  6. </dependency>
  7. 服务直接自动注入使用
  8. @Autowired
  9. private StringRedisTemplate stringRedisTemplate;

发表评论

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

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

相关阅读