经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
在SpringBoot中添加Redis及配置方法
来源:jb51  时间:2018/10/16 9:10:51  对本文有异议

在实际的开发中,会有这样的场景。有一个微服务需要提供一个查询的服务,但是需要查询的数据库表的数据量十分庞大,查询所需要的时间很长。 此时就可以考虑在项目中加入缓存。

引入依赖

在maven项目中引入如下依赖。并且需要在本地安装redis。

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

配置redis

在SpringBoot的配置文件中添加如下代码。

  1. redis:
  2.   host: 127.0.0.1
  3.   port: 6379
  4.   timeout: 5000
  5.   database: 0
  6.   jedis:
  7.    pool:
  8.     max-idle: 8
  9.     max-wait:
  10.     min-idle: 0

添加redis配置文件

新建名为RedisConfig的配置类。

  1. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  2. import com.fasterxml.jackson.annotation.PropertyAccessor;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import org.springframework.cache.CacheManager;
  5. import org.springframework.cache.annotation.CachingConfigurerSupport;
  6. import org.springframework.cache.annotation.EnableCaching;
  7. import org.springframework.cache.interceptor.KeyGenerator;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.data.redis.cache.RedisCacheConfiguration;
  11. import org.springframework.data.redis.cache.RedisCacheManager;
  12. import org.springframework.data.redis.cache.RedisCacheWriter;
  13. import org.springframework.data.redis.connection.RedisConnectionFactory;
  14. import org.springframework.data.redis.core.RedisTemplate;
  15. import org.springframework.data.redis.core.StringRedisTemplate;
  16. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  17.  
  18. import java.time.Duration;
  19.  
  20. /**
  21.  * RedisConfig
  22.  *
  23.  * @author detectiveHLH
  24.  * @date 2018-10-11 14:39
  25.  **/
  26. @Configuration
  27. @EnableCaching
  28. public class RedisConfig extends CachingConfigurerSupport {
  29.   @Bean
  30.   @Override
  31.   public KeyGenerator keyGenerator() {
  32.     return (target, method, params) -> {
  33.       StringBuilder sb = new StringBuilder();
  34.       sb.append(target.getClass().getName());
  35.       sb.append(method.getName());
  36.       for (Object obj : params) {
  37.         sb.append(obj.toString());
  38.       }
  39.       return sb.toString();
  40.     };
  41.   }
  42.  
  43.   @Bean
  44.   public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
  45.     ObjectMapper om = new ObjectMapper();
  46.     om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  47.     om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  48.     //redis序列化
  49.     Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  50.     jackson2JsonRedisSerializer.setObjectMapper(om);
  51.  
  52.     StringRedisTemplate template = new StringRedisTemplate(factory);
  53.     template.setValueSerializer(jackson2JsonRedisSerializer);
  54.     template.afterPropertiesSet();
  55.     return template;
  56.   }
  57.  
  58.   /**
  59.    * 自定义CacheManager
  60.    */
  61.   @Bean
  62.   public CacheManager cacheManager(RedisTemplate redisTemplate) {
  63.     //全局redis缓存过期时间
  64.     RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1));
  65.     RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
  66.     return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
  67.   }
  68. }

添加缓存配置

在项目的service层中的实现类中,添加@Cacheable注解。

  1. import java.util.HashMap;
  2.  
  3. /**
  4.  * UserLoginServiceImpl
  5.  *
  6.  * @author detectiveHLH
  7.  * @date 2018-10-10 17:20
  8.  **/
  9. @Service
  10. public class UserLoginServiceImpl implements UserLoginService {
  11.   @Autowired
  12.   private UserLoginMapper userLoginMapper;
  13.  
  14.   @Override
  15.   @Cacheable(value = "usercache")
  16.   public HashMap getByUserName(String userName) {
  17.     System.out.println("此时没有走缓存");
  18.     return userLoginMapper.getByUserName(userName);
  19.   }
  20. }

然后调用一次该接口。就可以在redis中看到如下的key。

"usercache::com.detectiveHLH.api.service.impl.UserLoginServiceImplgetByUserNameSolarFarm"

同时,可以在控制台中看到有"此时没有走缓存"的输出。然后再次调用该接口,就可以看到返回的速度明显变快,并且没有"此时没有走缓存"输出。说明 此时的接口走的是缓存。

总结

以上所述是小编给大家介绍的在SpringBoot中添加Redis及配置方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对w3xue网站的支持!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号