Spring-Data-Redis

Spring-data-redis是spring大家族的一部分,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装,RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。

基础配置

依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>com.alibaba</groupId>
  7. <artifactId>fastjson</artifactId>
  8. <version>1.2.61</version>
  9. </dependency>

application.yml

  1. spring:
  2. redis:
  3. host: 127.0.0.1
  4. port: 6379
  5. database: 1
  6. password:

自定义序列化配置(解决fastjson反序列化失败autoType is not support问题)

  1. /**
  2. * {@link RedisSerializer} FastJson Generic Impl
  3. * 解决fastjson反序列化失败autoType is not support问题, fastJson反序列化要求类中有默认的空参构造方法
  4. *
  5. * @author lihengming
  6. * @since 1.2.36
  7. */
  8. public class AutoTypeGenericFastJsonRedisSerializer implements RedisSerializer<Object> {
  9. private final static ParserConfig defaultRedisConfig = new ParserConfig();
  10. static {
  11. defaultRedisConfig.setAutoTypeSupport(true);
  12. defaultRedisConfig.addAccept("com.example.demo");
  13. }
  14. @Override
  15. public byte[] serialize(Object object) throws SerializationException {
  16. if (object == null) {
  17. return new byte[0];
  18. }
  19. try {
  20. return JSON.toJSONBytes(object, SerializerFeature.WriteClassName);
  21. } catch (Exception ex) {
  22. throw new SerializationException("Could not serialize: " + ex.getMessage(), ex);
  23. }
  24. }
  25. @Override
  26. public Object deserialize(byte[] bytes) throws SerializationException {
  27. if (bytes == null || bytes.length == 0) {
  28. return null;
  29. }
  30. try {
  31. return JSON.parseObject(new String(bytes, IOUtils.UTF8), Object.class, defaultRedisConfig);
  32. } catch (Exception ex) {
  33. throw new SerializationException("Could not deserialize: " + ex.getMessage(), ex);
  34. }
  35. }
  36. }

redis配置(设置序列化, 定义redisTemplate)

  1. /**
  2. * BizConfiguration
  3. *
  4. * @author Shenzhen Greatonce Co Ltd
  5. * @author ginta
  6. * @version 2019/3/7
  7. */
  8. @EnableCaching
  9. @Configuration
  10. public class BizConfiguration {
  11. @Bean
  12. AutoTypeGenericFastJsonRedisSerializer fastJsonRedisSerializer() {
  13. return new AutoTypeGenericFastJsonRedisSerializer();
  14. }
  15. @Bean
  16. public RedisCacheConfiguration redisCacheConfiguration() {
  17. return RedisCacheConfiguration.defaultCacheConfig()
  18. .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
  19. .serializeValuesWith(
  20. RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer()))
  21. .entryTtl(Duration.ofDays(30));
  22. }
  23. @Bean
  24. public RedisTemplate<String, Object> redisTemplate(
  25. RedisConnectionFactory redisConnectionFactory) {
  26. RedisTemplate<String, Object> template = new RedisTemplate<>();
  27. template.setConnectionFactory(redisConnectionFactory);
  28. template.setEnableDefaultSerializer(false);
  29. template.setKeySerializer(new StringRedisSerializer());
  30. template.setValueSerializer(fastJsonRedisSerializer());
  31. template.setHashKeySerializer(fastJsonRedisSerializer());
  32. template.setHashValueSerializer(fastJsonRedisSerializer());
  33. return template;
  34. }
  35. }

使用API操作基本redis基本数据类型

ValueOperations:字符串类型操作
ListOperations:列表类型操作
SetOperations:集合类型操作
ZSetOperations:有序集合类型操作
HashOperations:散列操作
示例:

  1. @Autowired
  2. RedisTemplate<String, Object> redisTemplate;
  3. 存:
  4. redisTemplate.opsForHash()
  5. .put(LubanConstants.LUBAN_AI_GENERATE_CALLBACK_PREFIX, image.getLubanImageId(), image);
  6. 取:
  7. Image image = redisTemplate.<String, Image>opsForHash()
  8. .get(LubanConstants.LUBAN_MICRO_EDIT_CALLBACK_PREFIX, targetId);

SpringCache+Redis

配置

如上, 加上自定义非null注解即可
自定义缓存非NULL注解

  1. /**
  2. * 缓存非NULL注解.
  3. *
  4. * @author ginta
  5. * @author Shenzhen Greatonce Co Ltd
  6. * @version 2018-07-19
  7. */
  8. @Target({ElementType.METHOD, ElementType.TYPE})
  9. @Retention(RetentionPolicy.RUNTIME)
  10. @Inherited
  11. @Documented
  12. @Cacheable
  13. public @interface CacheableNotNull {
  14. @AliasFor(annotation = Cacheable.class)
  15. String[] value() default {};
  16. @AliasFor(annotation = Cacheable.class)
  17. String[] cacheNames() default {};
  18. @AliasFor(annotation = Cacheable.class)
  19. String key() default "";
  20. @AliasFor(annotation = Cacheable.class)
  21. String keyGenerator() default "";
  22. @AliasFor(annotation = Cacheable.class)
  23. String cacheManager() default "";
  24. @AliasFor(annotation = Cacheable.class)
  25. String cacheResolver() default "";
  26. @AliasFor(annotation = Cacheable.class)
  27. String condition() default "";
  28. @AliasFor(annotation = Cacheable.class)
  29. String unless() default "#result == null";
  30. @AliasFor(annotation = Cacheable.class)
  31. boolean sync() default false;
  32. }

相关概念

Spring Cache是作用在方法上的,其核心思想是这样的:当我们在调用一个缓存方法时会把该方法参数和返回结果作为一个键值对存放在缓存中,等到下次利用同样的参数来调用该方法时将不再执行该方法,而是直接从缓存中获取结果进行返回。
**

相关注解

@Cacheable 触发缓存入口 (方法,类)

需要注意的是当一个支持缓存的方法在对象内部被调用时是不会触发缓存功能的。
@Cacheable可以指定三个属性,value(指定Cache名称)、key(支持SpringEL表达式,没有指定则为默认策略生成key)和condition(指定发生的条件)。

  1. value(指定Cache名称)
  2. @Cacheable("cache1")//Cache是发生在cache1上的
  3. @Cacheable({"cache1", "cache2"})//Cache是发生在cache1和cache2上的
  4. public User find(Integer id) {
  5. returnnull;
  6. }
  7. key(支持SpringEL表达式,没有指定则为默认策略生成key)
  8. springEL表达式(“#参数名”或者“#p参数index”)
  9. @Cacheable(value="users", key="#id")
  10. public User find(Integer id) {
  11. returnnull;
  12. }
  13. @Cacheable(value="users", key="#p0")
  14. public User find(Integer id) {
  15. returnnull;
  16. }
  17. @Cacheable(value="users", key="#user.id")
  18. public User find(User user) {
  19. returnnull;
  20. }
  21. @Cacheable(value="users", key="#p0.id")
  22. public User find(User user) {
  23. returnnull;
  24. }
  25. condition(指定发生的条件)
  26. @Cacheable(value={"users"}, key="#user.id", condition="#user.id%2==0")
  27. public User find(User user) {
  28. System.out.println("find user by user " + user);
  29. return user;
  30. }

除了上述使用方法参数作为key之外,Spring还为我们提供了一个root对象可以用来生成key。通过该root对象我们可以获取到以下信息。
image.png

@CacahePut 更新缓存

与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
可以指定的属性跟@Cacheable是一样的

@CacheEvict 触发移除缓存(方法,类)

可以指定的属性有value、key、condition、allEntries(allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false)和beforeInvocation( 清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。使用beforeInvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,Spring会在调用该方法之前清除缓存中的指定元素。)
**

@Caching 将多种缓存操作分组

Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。

  1. @Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),
  2. @CacheEvict(value = "cache3", allEntries = true) })
  3. public User find(Integer id) {
  4. returnnull;
  5. }

@CacheConfig 类级别的缓存注解,允许共享缓存名称

使用自定义注解

  1. @Target({ElementType.TYPE, ElementType.METHOD})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Cacheable(value="users")
  4. public @interface MyCacheable {
  5. }
  6. 那么在我们需要缓存的方法上使用@MyCacheable进行标注也可以达到同样的效果。
  7. @MyCacheable
  8. public User findById(Integer id) {
  9. System.out.println("find user by id: " + id);
  10. User user = new User();
  11. user.setId(id);
  12. user.setName("Name" + id);
  13. return user;
  14. }

使用示例

  1. 添加缓存:
  2. 租户
  3. 租户信息:TENANT_${tenantId}
  4. 租户OSS设置:OSS_SETTING_${tenantId}
  5. 店铺
  6. STORE_${tanantId}_${storeId}
  7. STORE_${tanantId}_UID_${userId}
  8. 品牌
  9. BRAND_${tanantId}_UID_${userId}
  10. 标签
  11. LABEL_${tanantId}_${labelId}
  12. 权限
  13. PRIVILEGE_${tanantId}_UID_${userId}_${privilegeType}
  14. 菜单
  15. NAVIGATION
  16. 模板库
  17. TEMPLATE_LIB_ROOT_${tanantId}_UID_${userId}
  18. 图片库
  19. IMAGE_LIB_ROOT_${tanantId}_UID_${userId}

注解使用:

  1. /**
  2. * 租户.
  3. *
  4. * @author 深圳市巨益软件有限公司
  5. * @version 1.0
  6. */
  7. @Service
  8. public class TenantServiceImpl extends AbstractService<Tenant, TenantQuery> implements TenantService {
  9. private static final String CACHE_NAME = "TENANT";
  10. @Autowired
  11. TenantDao dao;
  12. @Override
  13. protected QueryDao<Tenant, TenantQuery> getDAO() {
  14. return this.dao;
  15. }
  16. /**
  17. * 启用.
  18. */
  19. @Override
  20. public int enable(Tenant entity) {
  21. entity.setEnable(true);
  22. return dao.update(entity);
  23. }
  24. /**
  25. * 禁用.
  26. */
  27. @Override
  28. public int disable(Tenant entity) {
  29. entity.setEnable(false);
  30. return dao.update(entity);
  31. }
  32. @Override
  33. @CacheableNotNull(value = CACHE_NAME, key = "'CODE_'+#code")
  34. public Tenant getByCode(String code) {
  35. Tenant eg = new Tenant();
  36. eg.setEnable(true);
  37. eg.setTenantCode(code);
  38. return getByExample(eg);
  39. }
  40. @Override
  41. @CacheableNotNull(value = CACHE_NAME, key = "#id")
  42. public Tenant getByKey(Long id) {
  43. return super.getByKey(id);
  44. }
  45. @Override
  46. @Caching(evict = {
  47. @CacheEvict(value = CACHE_NAME, key = "#entity.tenantId"),
  48. @CacheEvict(value = CACHE_NAME, key = "'CODE_'+#entity.tenantCode")
  49. })
  50. public int modify(Tenant entity) {
  51. return super.modify(entity);
  52. }
  53. @Override
  54. @Caching(evict = {
  55. @CacheEvict(value = CACHE_NAME, key = "#entity.tenantId"),
  56. @CacheEvict(value = CACHE_NAME, key = "'CODE_'+#entity.tenantCode")
  57. })
  58. public int remove(Tenant entity) {
  59. return super.remove(entity);
  60. }
  61. }

image.png

Redis的发布订阅(pub/sub)

官方文档 https://spring.io/guides/gs/messaging-redis/
玩法: 配置上创建消息监听容器, 容器中加适配器和通道, 适配器中包裹着监听的类以及方法, 另外在适配器上,加上redis的序列化
然后发送消息, 监听类监听消息并处理即可
**

配置

参见官网配置

  1. package com.greatonce.tuya.service.consumer;
  2. import com.greatonce.tuya.util.json.AutoTypeGenericFastJsonRedisSerializer;
  3. import javax.annotation.Resource;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.data.redis.connection.RedisConnectionFactory;
  7. import org.springframework.data.redis.listener.PatternTopic;
  8. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
  9. import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
  10. /**
  11. * ConsumerConfiguration
  12. *
  13. * @author Shenzhen Greatonce Co Ltd
  14. * @author ginta
  15. * @version 2019/4/28
  16. */
  17. @Configuration
  18. public class ConsumerConfiguration {
  19. private AutoTypeGenericFastJsonRedisSerializer fastJsonRedisSerializer;
  20. public ConsumerConfiguration(AutoTypeGenericFastJsonRedisSerializer fastJsonRedisSerializer) {
  21. this.fastJsonRedisSerializer = fastJsonRedisSerializer;
  22. }
  23. /**
  24. * 创建一个监听消息容器:
  25. * 1.创建连接
  26. * 2.添加MessageListener,同时声明通道
  27. */
  28. @Bean
  29. RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
  30. MessageListenerAdapter listenerAdapter) {
  31. RedisMessageListenerContainer container = new RedisMessageListenerContainer();
  32. container.setConnectionFactory(connectionFactory);
  33. container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
  34. return container;
  35. }
  36. /**
  37. * 消息消费类包裹在消息监听适配器中:
  38. * 声明监听类以及方法
  39. */
  40. @Bean
  41. MessageListenerAdapter listenerAdapter(StoreMessageListener receiver) {
  42. MessageListenerAdapter adapter = new MessageListenerAdapter(receiver, "onStoreModified");
  43. adapter.setSerializer(fastJsonRedisSerializer);
  44. return adapter;
  45. }
  46. }

为多通道, 改进后的配置类

  1. package com.greatonce.tuya.service.consumer;
  2. import com.greatonce.tuya.util.json.AutoTypeGenericFastJsonRedisSerializer;
  3. import javax.annotation.Resource;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.data.redis.connection.RedisConnectionFactory;
  8. import org.springframework.data.redis.listener.PatternTopic;
  9. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
  10. import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
  11. /**
  12. * ConsumerConfiguration
  13. *
  14. * @author Shenzhen Greatonce Co Ltd
  15. * @author ginta
  16. * @version 2019/4/28
  17. */
  18. @Configuration
  19. public class ConsumerConfiguration {
  20. private AutoTypeGenericFastJsonRedisSerializer fastJsonRedisSerializer;
  21. public ConsumerConfiguration(AutoTypeGenericFastJsonRedisSerializer fastJsonRedisSerializer) {
  22. this.fastJsonRedisSerializer = fastJsonRedisSerializer;
  23. }
  24. @Resource
  25. StoreMessageListener storeMessageListener;
  26. @Resource
  27. MessageListenerAdapter storeModifiedAdapter;
  28. @Bean
  29. RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
  30. RedisMessageListenerContainer container = new RedisMessageListenerContainer();
  31. container.setConnectionFactory(connectionFactory);
  32. addMessageListener(container, storeModifiedAdapter, "STORE_MODIFIED");
  33. return container;
  34. }
  35. @Bean
  36. MessageListenerAdapter storeModifiedAdapter() {
  37. return createMessageListenerAdapter(storeMessageListener, "onStoreModified");
  38. }
  39. private void addMessageListener(RedisMessageListenerContainer container, MessageListenerAdapter adapter,
  40. String topic) {
  41. container.addMessageListener(adapter, new PatternTopic(topic));
  42. }
  43. private MessageListenerAdapter createMessageListenerAdapter(Object delegate, String defaultListenerMethod) {
  44. MessageListenerAdapter adapter = new MessageListenerAdapter(delegate, defaultListenerMethod);
  45. adapter.setSerializer(fastJsonRedisSerializer);
  46. return adapter;
  47. }
  48. }

使用

1.消息监听类

  1. /**
  2. * StoreMessageListener
  3. *
  4. * @author Shenzhen Greatonce Co Ltd
  5. * @author ginta
  6. * @version 2019/5/20
  7. */
  8. @Component
  9. public class StoreMessageListener {
  10. public void onStoreModified(Store message) {
  11. System.out.println("StoreMessageListener------->" + message);
  12. }
  13. }

2.发送消息

  1. @Override
  2. public int modify(Store entity) {
  3. int count = super.modify(entity);
  4. redisTemplate.convertAndSend("chat", entity);
  5. return count;
  6. }

Redis内存模型

参考: https://juejin.im/entry/5ae2c177f265da0b722ad90b