SpringBoot怎么整合Redis实现热点数据缓存

其他教程   发布日期:2023年08月24日   浏览次数:390

本篇内容主要讲解“SpringBoot怎么整合Redis实现热点数据缓存”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“SpringBoot怎么整合Redis实现热点数据缓存”吧!

我们以IDEA + SpringBoot作为 Java中整合Redis的使用 的测试环境

首先,我们需要导入Redis的maven依赖

  1. <!-- Redis的maven依赖包 -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>

其次,我们需要在配置文件中配置你的Redis配置信息,我使用的是 .yml文件格式

  1. # redis配置
  2. spring:
  3. redis:
  4. # r服务器地址
  5. host: 127.0.0.1
  6. # 服务器端口
  7. port: 6379
  8. # 数据库索引(默认0)
  9. database: 0
  10. # 连接超时时间(毫秒)
  11. timeout: 10s
  12. jedis:
  13. pool:
  14. # 连接池中的最大空闲连接数
  15. max-idle: 8
  16. # 连接池中的最小空闲连接数
  17. min-idle: 0
  18. # 连接池最大连接数(使用负值表示没有限制)
  19. max-active: 8
  20. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  21. max-wait: -1

对 redis 做自定义配置

  1. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  2. import com.fasterxml.jackson.annotation.JsonTypeInfo;
  3. import com.fasterxml.jackson.annotation.PropertyAccessor;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
  6. import org.springframework.cache.annotation.CachingConfigurerSupport;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
  10. import org.springframework.data.redis.core.RedisTemplate;
  11. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  12. import org.springframework.data.redis.serializer.StringRedisSerializer;
  13. @Configuration
  14. public class RedisConfigurer extends CachingConfigurerSupport {
  15. /**
  16. * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
  17. */
  18. @Bean
  19. public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
  20. // 配置redisTemplate
  21. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  22. redisTemplate.setConnectionFactory(lettuceConnectionFactory);
  23. // 设置序列化
  24. Jackson2JsonRedisSerializer<Object> redisSerializer = getRedisSerializer();
  25. // key序列化
  26. redisTemplate.setKeySerializer(new StringRedisSerializer());
  27. // value序列化
  28. redisTemplate.setValueSerializer(redisSerializer);
  29. // Hash key序列化
  30. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
  31. // Hash value序列化
  32. redisTemplate.setHashValueSerializer(redisSerializer);
  33. redisTemplate.afterPropertiesSet();
  34. return redisTemplate;
  35. }
  36. /**
  37. * 设置Jackson序列化
  38. */
  39. private Jackson2JsonRedisSerializer<Object> getRedisSerializer() {
  40. Jackson2JsonRedisSerializer<Object> redisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
  41. ObjectMapper om = new ObjectMapper();
  42. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  43. om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
  44. redisSerializer.setObjectMapper(om);
  45. return redisSerializer;
  46. }
  47. }

然后,我们需要创建一个RedisUtil来对Redis数据库进行操作

  1. package com.zyxx.test.utils;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * @ClassName RedisUtil
  7. * @Author
  8. * @Date 2019-08-03 17:29:29
  9. * @Version 1.0
  10. **/
  11. @Component
  12. public class RedisUtil {
  13. @Autowired
  14. private RedisTemplate<String, String> template;
  15. /**
  16. * 读取数据
  17. *
  18. * @param key
  19. * @return
  20. */
  21. public String get(final String key) {
  22. return template.opsForValue().get(key);
  23. }
  24. /**
  25. * 写入数据
  26. */
  27. public boolean set(final String key, String value) {
  28. boolean res = false;
  29. try {
  30. template.opsForValue().set(key, value);
  31. res = true;
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. return res;
  36. }
  37. /**
  38. * 根据key更新数据
  39. */
  40. public boolean update(final String key, String value) {
  41. boolean res = false;
  42. try {
  43. template.opsForValue().getAndSet(key, value);
  44. res = true;
  45. } catch (Exception e) {
  46. e.printStackTrace();
  47. }
  48. return res;
  49. }
  50. /**
  51. * 根据key删除数据
  52. */
  53. public boolean del(final String key) {
  54. boolean res = false;
  55. try {
  56. template.delete(key);
  57. res = true;
  58. } catch (Exception e) {
  59. e.printStackTrace();
  60. }
  61. return res;
  62. }
  63. /**
  64. * 是否存在key
  65. */
  66. public boolean hasKey(final String key) {
  67. boolean res = false;
  68. try {
  69. res = template.hasKey(key);
  70. } catch (Exception e) {
  71. e.printStackTrace();
  72. }
  73. return res;
  74. }
  75. /**
  76. * 给指定的key设置存活时间
  77. * 默认为-1,表示永久不失效
  78. */
  79. public boolean setExpire(final String key, long seconds) {
  80. boolean res = false;
  81. try {
  82. if (0 < seconds) {
  83. res = template.expire(key, seconds, TimeUnit.SECONDS);
  84. }
  85. } catch (Exception e) {
  86. e.printStackTrace();
  87. }
  88. return res;
  89. }
  90. /**
  91. * 获取指定key的剩余存活时间
  92. * 默认为-1,表示永久不失效,-2表示该key不存在
  93. */
  94. public long getExpire(final String key) {
  95. long res = 0;
  96. try {
  97. res = template.getExpire(key, TimeUnit.SECONDS);
  98. } catch (Exception e) {
  99. e.printStackTrace();
  100. }
  101. return res;
  102. }
  103. /**
  104. * 移除指定key的有效时间
  105. * 当key的有效时间为-1即永久不失效和当key不存在时返回false,否则返回true
  106. */
  107. public boolean persist(final String key) {
  108. boolean res = false;
  109. try {
  110. res = template.persist(key);
  111. } catch (Exception e) {
  112. e.printStackTrace();
  113. }
  114. return res;
  115. }
  116. }

最后,我们可以使用单元测试来检测我们在RedisUtil中写的操作Redis数据库的方法

  1. package com.zyxx.test;
  2. import com.zyxx.test.utils.RedisUtil;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.test.context.junit4.SpringRunner;
  7. import javax.annotation.Resource;
  8. @RunWith(SpringRunner.class)
  9. @SpringBootTest
  10. public class TestApplicationTest {
  11. @Resource
  12. private RedisUtil redisUtil;
  13. @Test
  14. public void setRedis() {
  15. boolean res = redisUtil.set("jay", "周杰伦 - 《以父之名》");
  16. System.out.println(res);
  17. }
  18. @Test
  19. public void getRedis() {
  20. String res = redisUtil.get("jay");
  21. System.out.println(res);
  22. }
  23. @Test
  24. public void updateRedis() {
  25. boolean res = redisUtil.update("jay", "周杰伦 - 《夜的第七章》");
  26. System.out.println(res);
  27. }
  28. @Test
  29. public void delRedis() {
  30. boolean res = redisUtil.del("jay");
  31. System.out.println(res);
  32. }
  33. @Test
  34. public void hasKey() {
  35. boolean res = redisUtil.hasKey("jay");
  36. System.out.println(res);
  37. }
  38. @Test
  39. public void expire() {
  40. boolean res = redisUtil.setExpire("jay", 100);
  41. System.out.println(res);
  42. }
  43. @Test
  44. public void getExpire() {
  45. long res = redisUtil.getExpire("jay");
  46. System.out.println(res);
  47. }
  48. @Test
  49. public void persist() {
  50. boolean res = redisUtil.persist("jay");
  51. System.out.println(res);
  52. }
  53. }
  • 推荐使用Redis客户端(redis-desktop-manager)来查看Redis数据库中的数据

  • 至此,我们在日常项目中整合Redis的基本使用操作就完成了,但在实际项目中,可能会涉及到更复杂的用法,可以根据你的业务需求调整Redis的使用即可。

以上就是SpringBoot怎么整合Redis实现热点数据缓存的详细内容,更多关于SpringBoot怎么整合Redis实现热点数据缓存的资料请关注九品源码其它相关文章!