Spring Boot使用redis做数据缓存

2023-05-16

1 添加redis支持

在pom.xml中添加

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

2 redis配置

  1. package com.wisely.ij.config;
  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.cache.CacheManager;
  6. import org.springframework.cache.annotation.CachingConfigurerSupport;
  7. import org.springframework.cache.annotation.EnableCaching;
  8. import org.springframework.cache.interceptor.KeyGenerator;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.data.redis.cache.RedisCacheManager;
  12. import org.springframework.data.redis.connection.RedisConnectionFactory;
  13. import org.springframework.data.redis.core.RedisTemplate;
  14. import org.springframework.data.redis.core.StringRedisTemplate;
  15. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  16. import java.lang.reflect.Method;
  17. @Configuration
  18. @EnableCaching
  19. public class RedisConfig extends CachingConfigurerSupport{
  20. @Bean
  21. public KeyGenerator wiselyKeyGenerator(){
  22. return new KeyGenerator() {
  23. @Override
  24. public Object generate(Object target, Method method, Object... params) {
  25. StringBuilder sb = new StringBuilder();
  26. sb.append(target.getClass().getName());
  27. sb.append(method.getName());
  28. for (Object obj : params) {
  29. sb.append(obj.toString());
  30. }
  31. return sb.toString();
  32. }
  33. };
  34. }
  35. @Bean
  36. public CacheManager cacheManager(
  37. @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
  38. return new RedisCacheManager(redisTemplate);
  39. }
  40. @Bean
  41. public RedisTemplate<String, String> redisTemplate(
  42. RedisConnectionFactory factory) {
  43. StringRedisTemplate template = new StringRedisTemplate(factory);
  44. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  45. ObjectMapper om = new ObjectMapper();
  46. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  47. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  48. jackson2JsonRedisSerializer.setObjectMapper(om);
  49. template.setValueSerializer(jackson2JsonRedisSerializer);
  50. template.afterPropertiesSet();
  51. return template;
  52. }
  53. }

3 redis服务器配置

  1. # REDIS (RedisProperties)
  2. spring.redis.database= # database name
  3. spring.redis.host=localhost # server host
  4. spring.redis.password= # server password
  5. spring.redis.port=6379 # connection port
  6. spring.redis.pool.max-idle=8 # pool settings ...
  7. spring.redis.pool.min-idle=0
  8. spring.redis.pool.max-active=8
  9. spring.redis.pool.max-wait=-1
  10. spring.redis.sentinel.master= # name of Redis server
  11. spring.redis.sentinel.nodes= # comma-separated list of host:port pairs

4 应用

测试两个实体类

  1. package com.wisely.ij.domain;
  2. public class Address {
  3. private Long id;
  4. private String province;
  5. private String city;
  6. public Address(Long id,String province, String city) {
  7. this.id = id;
  8. this.province = province;
  9. this.city = city;
  10. }
  11. public Address() {
  12. }
  13. public Long getId() {
  14. return id;
  15. }
  16. public void setId(Long id) {
  17. this.id = id;
  18. }
  19. public String getProvince() {
  20. return province;
  21. }
  22. public void setProvince(String province) {
  23. this.province = province;
  24. }
  25. public String getCity() {
  26. return city;
  27. }
  28. public void setCity(String city) {
  29. this.city = city;
  30. }
  31. }
  1. package com.wisely.ij.domain;
  2. public class User {
  3. private Long id;
  4. private String firstName;
  5. private String lastName;
  6. public User(Long id,String firstName, String lastName) {
  7. this.id = id ;
  8. this.firstName = firstName;
  9. this.lastName = lastName;
  10. }
  11. public User() {
  12. }
  13. public Long getId() {
  14. return id;
  15. }
  16. public void setId(Long id) {
  17. this.id = id;
  18. }
  19. public String getFirstName() {
  20. return firstName;
  21. }
  22. public void setFirstName(String firstName) {
  23. this.firstName = firstName;
  24. }
  25. public String getLastName() {
  26. return lastName;
  27. }
  28. public void setLastName(String lastName) {
  29. this.lastName = lastName;
  30. }
  31. }

使用演示

  1. package com.wisely.ij.service;
  2. import com.wisely.ij.domain.Address;
  3. import com.wisely.ij.domain.User;
  4. import org.springframework.cache.annotation.Cacheable;
  5. import org.springframework.stereotype.Service;
  6. /**
  7. * Created by wisely on 2015/5/25.
  8. */
  9. @Service
  10. public class DemoService {
  11. @Cacheable(value = "usercache",keyGenerator = "wiselyKeyGenerator")
  12. public User findUser(Long id,String firstName,String lastName){
  13. System.out.println("无缓存的时候调用这里");
  14. return new User(id,firstName,lastName);
  15. }
  16. @Cacheable(value = "addresscache",keyGenerator = "wiselyKeyGenerator")
  17. public Address findAddress(Long id,String province,String city){
  18. System.out.println("无缓存的时候调用这里");
  19. return new Address(id,province,city);
  20. }
  21. }
  1. package com.wisely.ij.web;
  2. import com.wisely.ij.domain.Address;
  3. import com.wisely.ij.domain.User;
  4. import com.wisely.ij.service.DemoService;
  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. /**
  10. * Created by wisely on 2015/5/25.
  11. */
  12. @Controller
  13. public class DemoController {
  14. @Autowired
  15. DemoService demoService;
  16. @RequestMapping("/test")
  17. @ResponseBody
  18. public String putCache(){
  19. demoService.findUser(1l,"wang","yunfei");
  20. demoService.findAddress(1l,"anhui","hefei");
  21. System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
  22. return "ok";
  23. }
  24. @RequestMapping("/test2")
  25. @ResponseBody
  26. public String testCache(){
  27. User user = demoService.findUser(1l,"wang","yunfei");
  28. Address address =demoService.findAddress(1l,"anhui","hefei");
  29. System.out.println("我这里没执行查询");
  30. System.out.println("user:"+"/"+user.getFirstName()+"/"+user.getLastName());
  31. System.out.println("address:"+"/"+address.getProvince()+"/"+address.getCity());
  32. return "ok";
  33. }
  34. }

5 检验

先访问http://localhost:8080/test 保存缓存

再访问http://localhost:8080/test2 调用缓存里的数据

http://wiselyman.iteye.com/blog/2184884

《整合 spring 4(包括mvc、context、orm) + mybatis 3 示例》一文简要介绍了最新版本的 Spring MVC、IOC、MyBatis ORM 三者的整合以及声明式事务处理。现在我们需要把缓存也整合进来,缓存我们选用的是 Redis,本文将在该文示例基础上介绍 Redis 缓存 + Spring 的集成。关于 Redis 服务器的搭建请参考博客《Redhat5.8 环境下编译安装 Redis 并将其注册为系统服务》。

1. 依赖包安装

pom.xml 加入:

  1. <!-- redis cache related.....start -->
  2. <dependency>
  3. <groupId>org.springframework.data</groupId>
  4. <artifactId>spring-data-redis</artifactId>
  5. <version>1.6.0.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>redis.clients</groupId>
  9. <artifactId>jedis</artifactId>
  10. <version>2.7.3</version>
  11. </dependency>
  12. <!-- redis cache related.....end -->

2. Spring 项目集成进缓存支持

要启用缓存支持,我们需要创建一个新的 CacheManager bean。CacheManager 接口有很多实现,本文演示的是和 Redis 的集成,自然就是用 RedisCacheManager 了。Redis 不是应用的共享内存,它只是一个内存服务器,就像 MySql 似的,我们需要将应用连接到它并使用某种“语言”进行交互,因此我们还需要一个连接工厂以及一个 Spring 和 Redis 对话要用的 RedisTemplate,这些都是 Redis 缓存所必需的配置,把它们都放在自定义的 CachingConfigurerSupport 中:

  1. /**
  2. * File Name:RedisCacheConfig.java
  3. *
  4. * Copyright Defonds Corporation 2015
  5. * All Rights Reserved
  6. *
  7. */
  8. package com.defonds.bdp.cache.redis;
  9. import org.springframework.cache.CacheManager;
  10. import org.springframework.cache.annotation.CachingConfigurerSupport;
  11. import org.springframework.cache.annotation.EnableCaching;
  12. import org.springframework.context.annotation.Bean;
  13. import org.springframework.context.annotation.Configuration;
  14. import org.springframework.data.redis.cache.RedisCacheManager;
  15. import org.springframework.data.redis.connection.RedisConnectionFactory;
  16. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
  17. import org.springframework.data.redis.core.RedisTemplate;
  18. /**
  19. *
  20. * Project Name:bdp
  21. * Type Name:RedisCacheConfig
  22. * Type Description:
  23. *  Author:Defonds
  24. * Create Date:2015-09-21
  25. *
  26. * @version
  27. *
  28. */
  29. @Configuration
  30. @EnableCaching
  31. public class RedisCacheConfig extends CachingConfigurerSupport {
  32. @Bean
  33. public JedisConnectionFactory redisConnectionFactory() {
  34. JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
  35. // Defaults
  36. redisConnectionFactory.setHostName("192.168.1.166");
  37. redisConnectionFactory.setPort(6379);
  38. return redisConnectionFactory;
  39. }
  40. @Bean
  41. public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
  42. RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
  43. redisTemplate.setConnectionFactory(cf);
  44. return redisTemplate;
  45. }
  46. @Bean
  47. public CacheManager cacheManager(RedisTemplate redisTemplate) {
  48. RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
  49. // Number of seconds before expiration. Defaults to unlimited (0)
  50. cacheManager.setDefaultExpiration(3000); // Sets the default expire time (in seconds)
  51. return cacheManager;
  52. }
  53. }

当然也别忘了把这些 bean 注入 Spring,不然配置无效。在 applicationContext.xml 中加入以下:

  1. <context:component-scan base-package="com.defonds.bdp.cache.redis" />

3. 缓存某些方法的执行结果

设置好缓存配置之后我们就可以使用 @Cacheable 注解来缓存方法执行的结果了,比如根据省份名检索城市的 provinceCities 方法和根据 city_code 检索城市的 searchCity 方法:

  1. // R
  2. @Cacheable("provinceCities")
  3. public List<City> provinceCities(String province) {
  4. logger.debug("province=" + province);
  5. return this.cityMapper.provinceCities(province);
  6. }
  7. // R
  8. @Cacheable("searchCity")
  9. public City searchCity(String city_code){
  10. logger.debug("city_code=" + city_code);
  11. return this.cityMapper.searchCity(city_code);
  12. }

4. 缓存数据一致性保证

CRUD (Create 创建,Retrieve 读取,Update 更新,Delete 删除) 操作中,除了 R 具备幂等性,其他三个发生的时候都可能会造成缓存结果和数据库不一致。为了保证缓存数据的一致性,在进行 CUD 操作的时候我们需要对可能影响到的缓存进行更新或者清除。

  1. // C
  2. @CacheEvict(value = { "provinceCities"}, allEntries = true)
  3. public void insertCity(String city_code, String city_jb,
  4. String province_code, String city_name,
  5. String city, String province) {
  6. City cityBean = new City();
  7. cityBean.setCityCode(city_code);
  8. cityBean.setCityJb(city_jb);
  9. cityBean.setProvinceCode(province_code);
  10. cityBean.setCityName(city_name);
  11. cityBean.setCity(city);
  12. cityBean.setProvince(province);
  13. this.cityMapper.insertCity(cityBean);
  14. }
  15. // U
  16. @CacheEvict(value = { "provinceCities", "searchCity" }, allEntries = true)
  17. public int renameCity(String city_code, String city_name) {
  18. City city = new City();
  19. city.setCityCode(city_code);
  20. city.setCityName(city_name);
  21. this.cityMapper.renameCity(city);
  22. return 1;
  23. }
  24. // D
  25. @CacheEvict(value = { "provinceCities", "searchCity" }, allEntries = true)
  26. public int deleteCity(String city_code) {
  27. this.cityMapper.deleteCity(city_code);
  28. return 1;
  29. }

业务考虑,本示例用的都是 @CacheEvict 清除缓存。如果你的 CUD 能够返回 City 实例,也可以使用 @CachePut 更新缓存策略。笔者推荐能用 @CachePut 的地方就不要用 @CacheEvict,因为后者将所有相关方法的缓存都清理掉,比如上面三个方法中的任意一个被调用了的话,provinceCities 方法的所有缓存将被清除。

5. 自定义缓存数据 key 生成策略

对于使用 @Cacheable 注解的方法,每个缓存的 key 生成策略默认使用的是参数名+参数值,比如以下方法:

  1. @Cacheable("users")
  2. public User findByUsername(String username)

这个方法的缓存将保存于 key 为 users~keys 的缓存下,对于 username 取值为 "赵德芳" 的缓存,key 为 "username-赵德芳"。一般情况下没啥问题,二般情况如方法 key 取值相等然后参数名也一样的时候就出问题了,如:

  1. @Cacheable("users")
  2. public Integer getLoginCountByUsername(String username)

这个方法的缓存也将保存于 key 为 users~keys 的缓存下。对于 username 取值为 "赵德芳" 的缓存,key 也为 "username-赵德芳",将另外一个方法的缓存覆盖掉。
解决办法是使用自定义缓存策略,对于同一业务(同一业务逻辑处理的方法,哪怕是集群/分布式系统),生成的 key 始终一致,对于不同业务则不一致:

  1. @Bean
  2. public KeyGenerator customKeyGenerator() {
  3. return new KeyGenerator() {
  4. @Override
  5. public Object generate(Object o, Method method, Object... objects) {
  6. StringBuilder sb = new StringBuilder();
  7. sb.append(o.getClass().getName());
  8. sb.append(method.getName());
  9. for (Object obj : objects) {
  10. sb.append(obj.toString());
  11. }
  12. return sb.toString();
  13. }
  14. };
  15. }

于是上述两个方法,对于 username 取值为 "赵德芳" 的缓存,虽然都还是存放在 key 为 users~keys 的缓存下,但由于 key 分别为 "类名-findByUsername-username-赵德芳" 和 "类名-getLoginCountByUsername-username-赵德芳",所以也不会有问题。
这对于集群系统、分布式系统之间共享缓存很重要,真正实现了分布式缓存。
笔者建议:缓存方法的 @Cacheable 最好使用方法名,避免不同的方法的 @Cacheable 值一致,然后再配以以上缓存策略。

6. 缓存的验证

6.1 缓存的验证

为了确定每个缓存方法到底有没有走缓存,我们打开了 MyBatis 的 SQL 日志输出,并且为了演示清楚,我们还清空了测试用 Redis 数据库。
先来验证 provinceCities 方法缓存,Eclipse 启动 tomcat 加载项目完毕,使用 JMeter 调用 /bdp/city/province/cities.json 接口:

Eclipse 控制台输出如下:

说明这一次请求没有命中缓存,走的是 db 查询。JMeter 再次请求,Eclipse 控制台输出:

标红部分以下是这一次请求的 log,没有访问 db 的 log,缓存命中。查看本次请求的 Redis 存储情况:

同样可以验证 city_code 为 1492 的 searchCity 方法的缓存是否有效:

图中标红部分是 searchCity 的缓存存储情况。

6.2 缓存一致性的验证

先来验证 insertCity 方法的缓存配置,JMeter 调用 /bdp/city/create.json 接口:

之后看 Redis 存储:

可以看出 provinceCities 方法的缓存已被清理掉,insertCity 方法的缓存奏效。
然后验证 renameCity 方法的缓存配置,JMeter 调用 /bdp/city/rename.json 接口:

之后再看 Redis 存储:

searchCity 方法的缓存也已被清理,renameCity 方法的缓存也奏效。

7. 注意事项

  1. 要缓存的 Java 对象必须实现 Serializable 接口,因为 Spring 会将对象先序列化再存入 Redis,比如本文中的 com.defonds.bdp.city.bean.City 类,如果不实现 Serializable 的话将会遇到类似这种错误:nested exception is java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.defonds.bdp.city.bean.City]]。
  2. 缓存的生命周期我们可以配置,然后托管 Spring CacheManager,不要试图通过 redis-cli 命令行去管理缓存。比如 provinceCities 方法的缓存,某个省份的查询结果会被以 key-value 的形式存放在 Redis,key 就是我们刚才自定义生成的 key,value 是序列化后的对象,这个 key 会被放在 key 名为 provinceCities~keys key-value 存储中,参考下图"provinceCities 方法在 Redis 中的缓存情况"。可以通过 redis-cli 使用 del 命令将 provinceCities~keys 删除,但每个省份的缓存却不会被清除。
  3. CacheManager 必须设置缓存过期时间,否则缓存对象将永不过期,这样做的原因如上,避免一些野数据“永久保存”。此外,设置缓存过期时间也有助于资源利用最大化,因为缓存里保留的永远是热点数据。
  4. 缓存适用于读多写少的场合,查询时缓存命中率很低、写操作很频繁等场景不适宜用缓存。

     后记

本文完整 Eclipse 下的开发项目示例已上传 CSDN 资源,有兴趣的朋友可以去下载下来参考:http://download.csdn.net/detail/defonds/9137505。

参考资料

    • Caching Data with Spring
    • 35. Cache Abstraction Part VII. Integration
    • Caching Data in Spring Using Redis
    • Caching with Spring Data Redis
    • spring-redis-caching-example

http://blog.csdn.net/defonds/article/details/48716161

本文介绍了如何使用注解的方式,将Redis缓存整合到你的Spring项目。

首先我们将使用jedis驱动,进而开始配置我们的Gradle。


  
  1. group 'com.gkatzioura.spring'
  2. version '1.0-SNAPSHOT'
  3. apply plugin: 'java'
  4. apply plugin: 'eclipse'
  5. apply plugin: 'idea'
  6. apply plugin: 'spring-boot'
  7. buildscript {
  8. repositories {
  9. mavenCentral()
  10. }
  11. dependencies {
  12. classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE")
  13. }
  14. }
  15. jar {
  16. baseName = 'gs-serving-web-content'
  17. version = '0.1.0'
  18. }
  19. sourceCompatibility = 1.8
  20. repositories {
  21. mavenCentral()
  22. }
  23. dependencies {
  24. compile "org.springframework.boot:spring-boot-starter-thymeleaf"
  25. compile 'org.slf4j:slf4j-api:1.6.6'
  26. compile 'ch.qos.logback:logback-classic:1.0.13'
  27. compile 'redis.clients:jedis:2.7.0'
  28. compile 'org.springframework.data:spring-data-redis:1.5.0.RELEASE'
  29. testCompile group: 'junit', name: 'junit', version: '4.11'
  30. }
  31. task wrapper(type: Wrapper) {
  32. gradleVersion = '2.3'
  33. }

紧接着我们将使用Spring注解,继续执行Redis装载配置。


  
  1. package com.gkatzioura.spring.config;
  2. import org.springframework.cache.CacheManager;
  3. import org.springframework.cache.annotation.CachingConfigurerSupport;
  4. import org.springframework.cache.annotation.EnableCaching;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.data.redis.cache.RedisCacheManager;
  8. import org.springframework.data.redis.connection.RedisConnectionFactory;
  9. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
  10. import org.springframework.data.redis.core.RedisTemplate;
  11. import org.springframework.data.redis.serializer.RedisSerializer;
  12. import org.springframework.data.redis.serializer.StringRedisSerializer;
  13. @Configuration
  14. @EnableCaching
  15. public class RedisConfig extends CachingConfigurerSupport {
  16. @Bean
  17. public JedisConnectionFactory redisConnectionFactory() {
  18. JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
  19. jedisConnectionFactory.setUsePool(true);
  20. return jedisConnectionFactory;
  21. }
  22. @Bean
  23. public RedisSerializer redisStringSerializer() {
  24. StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
  25. return stringRedisSerializer;
  26. }
  27. @Bean(name="redisTemplate")
  28. public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf,RedisSerializer redisSerializer) {
  29. RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
  30. redisTemplate.setConnectionFactory(cf);
  31. redisTemplate.setDefaultSerializer(redisSerializer);
  32. return redisTemplate;
  33. }
  34. @Bean
  35. public CacheManager cacheManager() {
  36. return new RedisCacheManager(redisTemplate(redisConnectionFactory(),redisStringSerializer()));
  37. }
  38. }

下一步将创建缓存接口CacheService。


  
  1. package com.gkatzioura.spring.cache;
  2. import java.util.Date;
  3. import java.util.List;
  4. public interface CacheService {
  5. public void addMessage(String user,String message);
  6. public List<String> listMessages(String user);
  7. }

当然用户既可以增加一条消息也能取回一条消息。因此,在实现过程中,用户相关信息的存在时间将默认设为一分钟。

我们用Redis来继承实现CacheService接口。


  
  1. package com.gkatzioura.spring.cache.impl;
  2. import com.gkatzioura.spring.cache.CacheService;
  3. import org.springframework.data.redis.core.ListOperations;
  4. import org.springframework.data.redis.core.RedisOperations;
  5. import org.springframework.data.redis.core.SetOperations;
  6. import org.springframework.stereotype.Service;
  7. import javax.annotation.Resource;
  8. import java.time.ZonedDateTime;
  9. import java.time.temporal.ChronoUnit;
  10. import java.util.Date;
  11. import java.util.List;
  12. @Service("cacheService")
  13. public class RedisService implements CacheService {
  14. @Resource(name = "redisTemplate")
  15. private ListOperations<String, String> messageList;
  16. @Resource(name = "redisTemplate")
  17. private RedisOperations<String,String> latestMessageExpiration;
  18. @Override
  19. public void addMessage(String user,String message) {
  20. messageList.leftPush(user,message);
  21. ZonedDateTime zonedDateTime = ZonedDateTime.now();
  22. Date date = Date.from(zonedDateTime.plus(1, ChronoUnit.MINUTES).toInstant());
  23. latestMessageExpiration.expireAt(user,date);
  24. }
  25. @Override
  26. public List<String> listMessages(String user) {
  27. return messageList.range(user,0,-1);
  28. }
  29. }

我们的缓存机制将保留每个用户发送的消息列表。为了实现这个功能我们将调用ListOperations接口,同时将每个user作为一个key键值。通过RedisOperations接口,我们可以为key设置特定存在时长。在本例中,主要使用的是 user key。

下一步我们将创建一个controller注入缓存服务。


  
  1. package com.gkatzioura.spring.controller;
  2. import com.gkatzioura.spring.cache.CacheService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.*;
  5. import java.util.List;
  6. @RestController
  7. public class MessageController {
  8. @Autowired
  9. private CacheService cacheService;
  10. @RequestMapping(value = "/message",method = RequestMethod.GET)
  11. @ResponseBody
  12. public List<String> greeting(String user) {
  13. List<String> messages = cacheService.listMessages(user);
  14. return messages;
  15. }
  16. @RequestMapping(value = "/message",method = RequestMethod.POST)
  17. @ResponseBody
  18. public String saveGreeting(String user,String message) {
  19. cacheService.addMessage(user,message);
  20. return "OK";
  21. }
  22. }

最后完成类Application的创建。


  
  1. package com.gkatzioura.spring;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class Application {
  6. public static void main(String[] args) {
  7. SpringApplication.run(Application.class, args);
  8. }
  9. }

经过如上步骤,接下来直接运行Application即可。

原文链接:Integrate Redis into a Spring Project( 译者/丘志鹏 审校/朱正贵 责编/仲浩)

http://www.csdn.net/article/2015-09-01/2825600

使用Spring Cache + Redis + Jackson Serializer缓存数据库查询结果中序列化问题的解决

应用场景

我们希望通过缓存来减少对关系型数据库的查询次数,减轻数据库压力。在执行DAO类的select***()query***()方法时,先从Redis中查询有没有缓存数据,如果有则直接从Redis拿到结果,如果没有再向数据库发起查询请求取数据。

序列化问题

要把domain object做为key-value对保存在redis中,就必须要解决对象的序列化问题。Spring Data Redis给我们提供了一些现成的方案:

  • JdkSerializationRedisSerializer. 使用JDK提供的序列化功能。 优点是反序列化时不需要提供类型信息(class),但缺点是序列化后的结果非常庞大,是JSON格式的5倍左右,这样就会消耗redis服务器的大量内存。
  • Jackson2JsonRedisSerializer. 使用Jackson库将对象序列化为JSON字符串。优点是速度快,序列化后的字符串短小精悍。
    但缺点也非常致命,那就是此类的构造函数中有一个类型参数,必须提供要序列化对象的类型信息(.class对象)。 通过查看源代码,发现其只在反序列化过程中用到了类型信息。

如果用方案一,就必须付出缓存多占用4倍内存的代价,实在承受不起。如果用方案二,则必须给每一种domain对象都配置一个Serializer,即如果我的应用里有100种domain对象,那就必须在spring配置文件中配置100个Jackson2JsonRedisSerializer,这显然是不现实的。

通过google, 发现spring data redis项目中有一个#145 pull request, 而这个提交请求的内容正是解决Jackson必须提供类型信息的问题。然而不幸的是这个请求还没有被merge。但我们可以把代码copy一下放到自己的项目中:


  
  1. /**
  2. * @author Christoph Strobl
  3. * @since 1.6
  4. */
  5. public class GenericJackson2JsonRedisSerializer implements RedisSerializer<Object> {
  6. private final ObjectMapper mapper;
  7. /**
  8. * Creates {@link GenericJackson2JsonRedisSerializer} and configures {@link ObjectMapper} for default typing.
  9. */
  10. public GenericJackson2JsonRedisSerializer() {
  11. this((String) null);
  12. }
  13. /**
  14. * Creates {@link GenericJackson2JsonRedisSerializer} and configures {@link ObjectMapper} for default typing using the
  15. * given {@literal name}. In case of an {@literal empty} or {@literal null} String the default
  16. * {@link JsonTypeInfo.Id#CLASS} will be used.
  17. *
  18. * @param classPropertyTypeName Name of the JSON property holding type information. Can be {@literal null}.
  19. */
  20. public GenericJackson2JsonRedisSerializer(String classPropertyTypeName) {
  21. this(new ObjectMapper());
  22. if (StringUtils.hasText(classPropertyTypeName)) {
  23. mapper.enableDefaultTypingAsProperty(DefaultTyping.NON_FINAL, classPropertyTypeName);
  24. } else {
  25. mapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.PROPERTY);
  26. }
  27. }
  28. /**
  29. * Setting a custom-configured {@link ObjectMapper} is one way to take further control of the JSON serialization
  30. * process. For example, an extended {@link SerializerFactory} can be configured that provides custom serializers for
  31. * specific types.
  32. *
  33. * @param mapper must not be {@literal null}.
  34. */
  35. public GenericJackson2JsonRedisSerializer(ObjectMapper mapper) {
  36. Assert.notNull(mapper, "ObjectMapper must not be null!");
  37. this.mapper = mapper;
  38. }
  39. /*
  40. * (non-Javadoc)
  41. * @see org.springframework.data.redis.serializer.RedisSerializer#serialize(java.lang.Object)
  42. */
  43. @Override
  44. public byte[] serialize(Object source) throws SerializationException {
  45. if (source == null) {
  46. return SerializationUtils.EMPTY_ARRAY;
  47. }
  48. try {
  49. return mapper.writeValueAsBytes(source);
  50. } catch (JsonProcessingException e) {
  51. throw new SerializationException("Could not write JSON: " + e.getMessage(), e);
  52. }
  53. }
  54. /*
  55. * (non-Javadoc)
  56. * @see org.springframework.data.redis.serializer.RedisSerializer#deserialize(byte[])
  57. */
  58. @Override
  59. public Object deserialize(byte[] source) throws SerializationException {
  60. return deserialize(source, Object.class);
  61. }
  62. /**
  63. * @param source can be {@literal null}.
  64. * @param type must not be {@literal null}.
  65. * @return {@literal null} for empty source.
  66. * @throws SerializationException
  67. */
  68. public <T> T deserialize(byte[] source, Class<T> type) throws SerializationException {
  69. Assert.notNull(type,
  70. "Deserialization type must not be null! Pleaes provide Object.class to make use of Jackson2 default typing.");
  71. if (SerializationUtils.isEmpty(source)) {
  72. return null;
  73. }
  74. try {
  75. return mapper.readValue(source, type);
  76. } catch (Exception ex) {
  77. throw new SerializationException("Could not read JSON: " + ex.getMessage(), ex);
  78. }
  79. }
  80. }

然后在配置文件中使用这个GenericJackson2JsonRedisSerializer:


  
  1. <bean id="jacksonSerializer" class="com.fh.taolijie.component.GenericJackson2JsonRedisSerializer">
  2. </bean>

重新构建部署,我们发现这个serializer可以同时支持多种不同类型的domain对象,问题解决。

http://www.myexception.cn/database/1958643.html

spring-data-redis提供了多种serializer策略,这对使用jedis的开发者而言,实在是非常便捷。sdr提供了4种内置的serializer:

  • JdkSerializationRedisSerializer:使用JDK的序列化手段(serializable接口,ObjectInputStrean,ObjectOutputStream),数据以字节流存储
  • StringRedisSerializer:字符串编码,数据以string存储
  • JacksonJsonRedisSerializer:json格式存储
  • OxmSerializer:xml格式存储

其中JdkSerializationRedisSerializer和StringRedisSerializer是最基础的序列化策略,其中“JacksonJsonRedisSerializer”与“OxmSerializer”都是基于stirng存储,因此它们是较为“高级”的序列化(最终还是使用string解析以及构建java对象)。

RedisTemplate中需要声明4种serializer,默认为“JdkSerializationRedisSerializer”:

1) keySerializer :对于普通K-V操作时,key采取的序列化策略
    2) valueSerializer:value采取的序列化策略
    3) hashKeySerializer: 在hash数据结构中,hash-key的序列化策略
    4) hashValueSerializer:hash-value的序列化策略

无论如何,建议key/hashKey采用StringRedisSerializer。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Boot使用redis做数据缓存 的相关文章

  • android onNewIntent 调用时机

    当前Activity已经在Activity堆栈当中时 xff0c 主要取决于LaunchMode对应的设置 LaunchMode为SingleTop时 xff0c 如果ActivityA在栈顶 且现在要再启动ActivityA xff0c
  • 不知道怎么开发VR游戏?Unity5.3官方VR教程重磅登场-系列3 VR中的交互方式

    不知道怎么开发VR游戏 xff1f Unity5 3官方VR教程重磅登场 系列3 VR中的交互方式 王寒 4 个月前 https zhuanlan zhihu com p 20505470 概览 xff1a 在VR项目中 xff0c 我们需
  • Java多线程通信-利用传统的线程通信wait(),notify()方法实现“生产者消费者模式”

    想利用传统的线程通信wait notify xff0c notifyAll 方法 xff0c 必须依赖于同步监听器的存在 xff0c 也就是说 xff0c 对于synchronized修饰的同步方法 xff0c 因为该类的默认实例 xff0
  • java TCP/IP实现简单的多人聊天功能

    TCP IP是可靠的网络协议 xff0c 数据的传输需要服务端和客户端之间三次 握手 xff0c 比较适合文本等一些可靠性要求高的数据传输 xff0c 但是它的效率较UDP低 下面通过一张图来简要说明使用 ServerSocket 创建 T
  • JavaScript开发工具WebStorm使用教程:从命令行运行代码检查

    从命令行运行代码检查 WebStorm运行代码检查可以发现并突出显示语法错误 死代码 可能的错误 错误的编码风格和其他问题 还可以从命令行为特定项目运行所有已配置的检查 xff0c 并将结果存储为 XML JSON 或带有报告的纯文本文件
  • 基于Spark的机器学习经验

    这篇内容基于我去年的一些感悟写的 xff0c 但是今年才在Stuq 的微信群做的分享 从技术角度而言 xff0c 对Spark的掌握和使用还是显得很手生的 但是今天一位做数据分析相关的朋友说 xff0c 受这篇内容影响 xff0c 他接受了
  • Linux(manjaro)微信web开发者工具

    安装 wine和winetricks span class hljs built in sudo span pacman S wine winetricks 打开winetricks 安装需要的组件 安装linux版本运行程序 github
  • C++类与对象

    C 43 43 面向对象 一 面向对象程序设计方法概述 1 凡是以类对象为基本构成单位的程序称为基于对象的程序 2 面向对象和面向过程的区别 xff1a 在笔者看来 xff0c 通俗地讲 xff0c 面向对象 就是在描述一个对象 xff0c
  • SVN无法提交修改问题

    分享一下我老师大神的人工智能教程 xff01 零基础 xff0c 通俗易懂 xff01 http blog csdn net jiangjunshow 也欢迎大家转载本篇文章 分享知识 xff0c 造福人民 xff0c 实现我们中华民族伟大
  • AbstractApplicationContext.refresh()应用上下文刷新方法

    前情提要 学习源码光看博客文章基本没有记住的可能 结合源码和博客 43 实践才能够通过理解记住 看了很多天才断断续续看完 发现它和其他IOC Bean生命周期都有关联 将之前片段式的认知串联起来了 这个刷新的代码很长 建议没耐心的时候就先不
  • IIC协议--简要理解

    1 iic协议是什么 xff1f IIC Inter xff0d Integrated Circuit 总线是一种由 PHILIPS 公司开发的两线式串行总线 xff0c 用于连接微控制器及其外围设备 它是由数据线 SDA 和时钟 SCL
  • RISC与CISC比较

    RISC的设计重点在于降低由硬件执行指令的复杂度 xff0c 因为软件比硬件容易提供更大的灵活性和更高的智能 xff0c 因此RISC设计对编译器有更高的要求 xff1b CISC的设计则更侧重于硬件执行指令的功能 xff0c 使CISC的
  • 操作系统选择调度方式和算法的若干准则

    1 调度的类型 按调度的层次 xff1a 长期 xff08 长程 作业 高级 xff09 调度 xff1b 中期 xff08 中级 中程 xff09 调度 xff1b 短期 xff08 短程 进程 低级 xff09 调度 按OS 的类型 x
  • 提灯过桥问题

    题目 xff1a 小明一家过一座桥 xff0c 过桥时是黑夜 xff0c 所以必须有灯 现在小明过桥要1秒 xff0c 小明的弟弟要3秒 xff0c 小明的爸爸要6秒 xff0c 小明的妈妈要8秒 xff0c 小明的爷爷要12秒 每次此桥最
  • 如何判断一个整数数组中是否有重复元素

    题目 xff1a 写一个函数判断一个int类型的数组是否是有效的 所谓有效是指 xff1a 假设数组大小为n xff0c 那么这个int数组里的值为0 n 1之间的数 xff0c 并且每个数只能出现一次 xff0c 否则就是无效数组 例如
  • 2014百度校招开发测试工程师笔试题

    时间 xff1a 2013 9 28 地点 xff1a 深圳 职位 xff1a 开发测试工程师
  • Spark Streaming + Spark SQL 实现配置化ETL流程

    Spark Streaming 非常适合ETL 但是其开发模块化程度不高 xff0c 所以这里提供了一套方案 xff0c 该方案提供了新的API用于开发Spark Streaming程序 xff0c 同时也实现了模块化 xff0c 配置化
  • 整体了解HADOOP框架及一些开源项目

    Hadoop框架中 xff0c 有很多优秀的工具 xff0c 帮助我们解决工作中的问题 Hadoop的位置 从上图可以看出 xff0c 越往右 xff0c 实时性越高 xff0c 越往上 xff0c 涉及到算法等越多 越往上 xff0c 越
  • Kafka简介

    Kafka简介 在当前的大数据时代 xff0c 第一个挑战是海量数据的收集 xff0c 另一个就是这些数据的分析 数据分析的类型通常有用户行为数据 应用性能跟踪数据 活动数据日志 事件消息等 消息发布机制用于连接各种应用并在它们之间路由消息
  • Flume入门笔记------架构以及应用介绍

    在具体介绍本文内容之前 xff0c 先给大家看一下Hadoop业务的整体开发流程 xff1a 从Hadoop的业务开发流程图中可以看出 xff0c 在大数据的业务处理过程中 xff0c 对于数据的采集是十分重要的一步 xff0c 也是不可避

随机推荐

  • 分布式服务框架dubbo原理解析

    alibaba有好几个分布式框架 xff0c 主要有 xff1a 进行远程调用 类似于RMI的这种远程调用 的 dubbo hsf xff0c jms消息服务 napoli notify xff0c KV数据库 tair 等 这个框架 工具
  • Android Studio Gradle project Sync Failed解决方法

    1 查看项目使用的gradle和本地gradle是否一致 本地gradle一般目录在C Users admin gradle文件夹下面 项目使用的gradle在项目的gradle wrapper properties文件中 distribu
  • Docker not running on windows 10 error: Hardware assisted virtualization and data execution protecti

    Docker not running on windows 10 error Hardware assisted virtualization and data execution protection must be enabled in
  • [高通SDM450][Android9.0]user版本uartlog常开

    文章目录 开发平台基本信息问题描述解决方法user版本调试串口可输入user版本uartlog常开 开发平台基本信息 芯片 SDM450 版本 Android 9 0 kernel msm 4 9 问题描述 user版本调试串口默认只输入调
  • Ubuntu 7.04 乱码解决

    一 解决XMMS乱码问题 菜单乱码的解决 1 sudo ln s etc gtk gtkrc zh CN etc gtk gtkrc zh CN utf 8 2 sudo gedit etc gtk gtkrc zh CN utf 8 填写
  • yii2连接websocket服务实现服务端主动推送消息给客户端

    上一篇写的是websocket的服务 xff0c 这一篇写写调用服务和web端调用 xff0c 接收消息部分 1 调用websocket服务 主动推送消息的方法 lt php namespace common services use co
  • 生产者消费者算法

    span class hljs comment include lt unistd h gt span span class hljs comment include lt stdlib h gt span span class hljs
  • MongoDB ODM 框架MongoMongo-简化你的数据存储

    MongMongo是一个用Java写的ODM框架 xff0c 使得对MongoDB的操作更加便捷 MongoMongo努力为Java开发者提供类似于ActiveORM 或者 Hibernate的操作API 并且保留了MongoDB的sche
  • archlinux安装deb软件步骤

    archlinux安装deb软件步骤 步骤 步骤 安装yay安装debtap安装转换出的pkg软件 注意事项 xff1a 安装yay问题解决 xff1a go语言相关安装debtap问题解决 xff1a git代理设置
  • 第六章 正则,BeautifulSoup,xpath

    文章目录 1 正则1 1 提取字符串1 2 替换1 3 搜索 2 beautifulsoup2 1 各种解析器2 2 提取方式2 3 find方法2 3 1 find2 3 2 find all2 3 3 通过id和类型精确定位2 3 3
  • spring如何获取bean的6种方法,你知道几个?

    spring获取bean的6种方法 Bean工厂 xff08 com springframework beans factory BeanFactory xff09 是Spring框架最核心的接口 xff0c 它提供了高级IoC的配置机制
  • c语言中while与do while循环的主要区别是什么

    while循环与do while循环的区别如下 xff1a 1 循环结构的表达式不同 while循环结构的表达式为 xff1a while xff08 表达式 xff09 循环体 xff1b do while循环结构的表达式为 xff1a
  • MVC设计模式

    MVC的全名是Model View Controller xff0c 是模型 Model xff0d 视图 view xff0d 控制器 controller 的缩写 xff0c 是一种设计模式 它是用一种业务逻辑 数据与界面显示分离的方法
  • MVC 模式及其优缺点

    一 MVC 原理 MVC 是一种程序开发设计模式 它实现了显示模块与功能模块的分离 提高了程序的可维 护性 可移植性 可扩展性与可重用性 xff0c 降低了程序的开发难度 它主要分模型 视图 控制器三层 1 模型 model 它是应用程序的
  • MVC 模式及其优缺点

    一 MVC 原理 MVC 是一种程序开发设计模式 它实现了显示模块与功能模块的分离 提高了程序的可维 护性 可移植性 可扩展性与可重用性 xff0c 降低了程序的开发难度 它主要分模型 视图 控制器三层 1 模型 model 它是应用程序的
  • MyBatis生命周期2的过程(最终)?

    首先加载mybatis config xml总配置文件 xff0c 根据development的参数配置连接数据库 xff1b 查询mappers映射关系 xff0c 找到mapper xml配置文件 执行mapper xml文件 xff0
  • spring boot使用redis做数据缓存

    1 添加redis支持 在pom xml中添加 1 lt dependency gt 2 lt groupId gt org springframework boot lt groupId gt 3 lt artifactId gt spr
  • Springboot配置支持Redis实例

    思路 xff1a 既然使用redis就要添加redis依赖 xff0c redis是 lt key value gt 的存储方式 xff0c 支持字符串存储 有了jar包 xff0c 就要把我们的数据存进去 xff0c 读出来 redis不
  • 【深度学习】显卡驱动, cuda, cudnn的关系与版本对应问题

    转载自 xff1a https blog csdn net weixin 39673002 article details 113053729 仅作学习记录 文章目录 显卡驱动cuda与cudnncudnncuda 建议 这四者从底层 xf
  • Spring Boot使用redis做数据缓存

    1 添加redis支持 在pom xml中添加 lt dependency gt lt groupId gt org springframework boot lt groupId gt lt artifactId gt spring bo