当前位置:   article > 正文

SpringBoot自定义spring-boot-redis-starter_spring-boot-starter-redis

spring-boot-starter-redis

目录

1. springboot 自定义的 starter 的用途

2. 自定义 Spring Boot Starter 可以用于各种场景

3. 以自定义 redis-starter 为例

3.1 自定义读取配置文件类

3.2 自定义 RedisTemplateAutoConfiguration

3.3 自定义 redis 缓存配置

3.4 自定义reids Lettuce 连接池

3.6 自定义 spring.factories 文件

3.7 在其他模块测试自定义的starter


1. springboot 自定义的 starter 的用途

        Spring Boot Starter 是一种用于简化 Spring Boot 应用程序依赖项管理的方式。它们是一组预定义的依赖项,可以将它们添加到您的应用程序中,以便您可以更轻松地配置和使用 Spring Boot 应用程序中的各种功能。

        自定义 Spring Boot Starter 可以帮助您将自己的库或框架集成到 Spring Boot 应用程序中。通过创建自己的 Starter,您可以将所有必需的依赖项打包到一个单独的模块中,并提供一个简单的配置方式,以便其他开发人员可以轻松地使用您的库或框架。

自定义 Spring Boot Starter 的主要用途包括:

        1. 简化依赖项管理:通过将所有必需的依赖项打包到一个单独的模块中,您可以简化其他开发人员使用您的库或框架的过程。

        2. 提供简单的配置方式:通过提供一个简单的配置方式,您可以使其他开发人员更轻松地配置和使用您的库或框架。

        3. 提供自定义的自动配置:通过提供自定义的自动配置,您可以使您的库或框架更容易地集成到 Spring Boot 应用程序中。

2. 自定义 Spring Boot Starter 可以用于各种场景

        1. 数据库访问:您可以创建一个自定义 Starter,用于简化数据库访问的配置和使用。例如,您可以创建一个 Starter,用于集成 MyBatis 或 Hibernate 等 ORM 框架。

        2. 缓存:您可以创建一个自定义 Starter,用于简化缓存的配置和使用。例如,您可以创建一个 Starter,用于集成 Redis 或 Ehcache 等缓存框架。

        3. 消息队列:您可以创建一个自定义 Starter,用于简化消息队列的配置和使用。例如,您可以创建一个 Starter,用于集成 RabbitMQ 或 Kafka 等消息队列框架。

        4. 安全性:您可以创建一个自定义 Starter,用于简化安全性的配置和使用。例如,您可以创建一个 Starter,用于集成 Spring Security 或 OAuth2 等安全框架。

        5. 日志:您可以创建一个自定义 Starter,用于简化日志的配置和使用。例如,您可以创建一个 Starter,用于集成 Log4j2 或 Logback 等日志框

3. 以自定义 redis-starter 为例

  3.1 自定义读取配置文件类

        自定义 starter 必要的 配置类, 用于读取yml或properties中的配置,  目的是为了在不同的模块都可以引入我们的自定义配置

  1. /**
  2. * @author yukun.yan
  3. * @description RedisTemplateConfigProperties
  4. * @date 2023/5/4 17:18
  5. */
  6. @Data
  7. @PropertySource(value = "classpath:sp-redis.properties")
  8. @ConfigurationProperties(prefix = "sp.redis")
  9. public class RedisTemplateConfigProperties {
  10. private String host;
  11. private String password;
  12. private int port;
  13. private int database;
  14. private int minIdle;
  15. private int maxIdle;
  16. private int maxTotal;
  17. private int timeout;
  18. private int expire;
  19. private int maxWait;
  20. }

        以及配置文件前缀, 这个不配置具体的参数, 目的是为了在其他模块配置

  1. sp.redis.database=
  2. sp.redis.password=
  3. sp.redis.port=
  4. sp.redis.host=
  5. sp.redis.timeout=
  6. sp.redis.min-idle=
  7. sp.redis.max-idle=
  8. sp.redis.max-total=
  9. sp.redis.expire=
  10. sp.redis.max-wait=
  11. sp.redis.enable=

3.2 自定义 RedisTemplateAutoConfiguration

        这里需要用到一个关键的主键, @AutoConfigureBefore(RedisAutoConfiguration.class) 

顾名思义, 这个注解的意思是在 RedisAutoConfiguration.class 注入之前去注入我们自定义的 RedisTemplateAutoConfiguration 中配置的 bean, 不然会出现这样的错误 :

         错误的原因是, springboot 在启动时会优先加载 springboot 框架自带的 spring.factories 文件中的定义的自动配置类, 把框架原本的 redisTemplate 作为 bean 注入到 容器中, 之后才会加载我们自定义的 RedisTemplateAutoConfiguration, 并且再次把我们魔改过 redisTemplate 注入到 bean 中, 这样容器中出现了2个名字一样的 redisTemplate, 所以会出现上述的错误

        我们自定义的 redis-starter 的目的是想让框架加载我们魔改后的 redisTemplate, 结合源码发现, 框架只会在缺失 redisTemplate 这个 bean 的时候才会加载框架自带的 redisTemplate, 源码位置 : org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration

        所以我们可以使用 @AutoConfigureBefore(RedisAutoConfiguration.class)  这个注解, 让框架优先加载我们自定义的 redisTemplate, 并注入到容器中, 之后框架在加载原本的 RedisAutoConfiguration 时候, 通过注解 @ConditionalOnMissingBean(name = "redisTemplate") 来控制不再做加载

  1. /**
  2. * @author yukun.yan
  3. * @description RedisTemplateAutoConfiguration redis操作类自动装配
  4. * @date 2023/5/4 16:43
  5. */
  6. @AutoConfigureBefore(RedisAutoConfiguration.class)
  7. @PropertySource(value = "classpath:sp-redis.properties")
  8. @EnableConfigurationProperties({RedisTemplateConfigProperties.class}) // 依赖配置文件
  9. public class RedisTemplateAutoConfiguration {
  10. /**
  11. * com.fasterxml.jackson.databind.deser.BeanDeserializer
  12. * ObjectMapper om = new ObjectMapper(); 调用 vanillaDeserialize方法
  13. * ObjectMapper om = mapperBuilder.build(); 调用 deserializeFromObject方法
  14. */
  15. @Bean
  16. public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory, Jackson2ObjectMapperBuilder mapperBuilder) {
  17. // Json序列化配置
  18. Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
  19. // ObjectMapper om = new ObjectMapper();
  20. ObjectMapper om = mapperBuilder.build();
  21. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  22. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  23. // 如果enableDefaultTyping过期(SpringBoot后续版本过期了)
  24. jackson2JsonRedisSerializer.setObjectMapper(om);
  25. // String的序列化配置
  26. StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
  27. RedisTemplate<String, Object> template = new RedisTemplate<>();
  28. template.setConnectionFactory(lettuceConnectionFactory);
  29. // key采用String的序列化方式
  30. template.setKeySerializer(stringRedisSerializer);
  31. // hash的key也采用String的序列化方式
  32. template.setHashKeySerializer(stringRedisSerializer);
  33. // value序列化方式采用jackson
  34. template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  35. // hash的value序列化方式采用jackson
  36. template.setHashValueSerializer(jackson2JsonRedisSerializer);
  37. // 刷新属性设置
  38. template.afterPropertiesSet();
  39. return template;
  40. }
  41. @Bean
  42. public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
  43. StringRedisTemplate template = new StringRedisTemplate();
  44. template.setConnectionFactory(lettuceConnectionFactory);
  45. // String 的序列化
  46. StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
  47. template.setKeySerializer(stringRedisSerializer);
  48. template.setValueSerializer(stringRedisSerializer);
  49. template.setHashKeySerializer(stringRedisSerializer);
  50. return template;
  51. }
  52. }

3.3 自定义 redis 缓存配置

        同样的,  @AutoConfigureAfter({RedisTemplateAutoConfiguration.class}) 这个注解是规定在我们自定义的 RedisTemplateAutoConfiguration 执行完毕之后, 在加载缓存配置, 否则在没有 redis 的情况下, 加载缓存没有意义

  1. /**
  2. * @author yukun.yan
  3. * @description RedisCacheAutoConfiguration redis缓存自动配置
  4. * @date 2023/5/5 10:15
  5. */
  6. @AutoConfigureAfter({RedisAutoConfiguration.class})
  7. @ConditionalOnMissingBean({CacheManager.class})
  8. @EnableConfigurationProperties(CacheProperties.class)
  9. public class RedisCacheAutoConfiguration {
  10. /**
  11. * 实例化自定义的缓存管理器
  12. */
  13. @Bean
  14. @SuppressWarnings(value = {"rawtypes"})
  15. public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
  16. RedisConnectionFactory redisConnectionFactory = Objects.requireNonNull(redisTemplate.getConnectionFactory());
  17. RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
  18. RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
  19. return new CustomRedisCacheManager(redisCacheWriter, redisCacheConfiguration);
  20. }
  21. /**
  22. * 自定义缓存规则
  23. */
  24. private static class CustomRedisCacheManager extends RedisCacheManager {
  25. public CustomRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
  26. super(cacheWriter, defaultCacheConfiguration);
  27. }
  28. @Override
  29. protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
  30. String[] cells = StringUtils.delimitedListToStringArray(name, "#");
  31. name = cells[0];
  32. if (cells.length > 1) {
  33. long ttl = Long.parseLong(cells[1]);
  34. // 根据传参设置缓存失效时间,默认单位是秒
  35. cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));
  36. }
  37. return super.createRedisCache(name, cacheConfig);
  38. }
  39. }
  40. }

3.4 自定义reids Lettuce 连接池

        如果没有连接池的话, SpringBoot2.0 版本之后 spring-boot-starter-data-redis 的底层默认使用了 Lettuce 来操作 redis ,早期的版本使用的是Jedis

        使用 @Primary 注解来标注我们自定义的 Lettuce 连接池为主连接池

  1. /**
  2. * @author yukun.yan
  3. * @description LettuceConnectionAutoConfiguration redis连接池自动配置
  4. * @date 2023/5/5 10:24
  5. */
  6. @AutoConfigureAfter({RedisAutoConfiguration.class}) // 之后配置链接工厂
  7. @EnableConfigurationProperties({RedisTemplateConfigProperties.class}) // 依赖配置文件
  8. @ConditionalOnBean({RedisTemplate.class, RedisConnectionFactory.class, RedisTemplateConfigProperties.class})
  9. public class LettuceConnectionAutoConfiguration {
  10. /**
  11. * 配置连接池信息
  12. * 容器在缺失 RedisConnectionFactory 配置的时候, 会兜底注入 JedisConnectionFactory
  13. * @see JedisConnectionConfiguration#redisConnectionFactory(org.springframework.beans.factory.ObjectProvider)
  14. *
  15. * @param properties
  16. * @return
  17. */
  18. @Bean
  19. @Primary
  20. public LettuceConnectionFactory lettuceConnectionFactory(final RedisTemplateConfigProperties properties) {
  21. // 基础配置
  22. RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
  23. redisStandaloneConfiguration.setDatabase(properties.getDatabase());
  24. redisStandaloneConfiguration.setHostName(properties.getHost());
  25. redisStandaloneConfiguration.setPort(properties.getPort());
  26. redisStandaloneConfiguration.setPassword(RedisPassword.of(properties.getPassword()));
  27. // 连接池配置
  28. LettucePoolingClientConfiguration lettuceClientConfiguration = LettucePoolingClientConfiguration
  29. .builder()
  30. .commandTimeout(Duration.ofMillis(properties.getTimeout()))
  31. .poolConfig(getPoolConfig(properties)).build();
  32. // 根据配置和客户端配置创建连接
  33. LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration, lettuceClientConfiguration);
  34. lettuceConnectionFactory.afterPropertiesSet();
  35. return lettuceConnectionFactory;
  36. }
  37. /**
  38. * 获取连接池配置
  39. *
  40. * @param properties
  41. * @return
  42. */
  43. private GenericObjectPoolConfig getPoolConfig(final RedisTemplateConfigProperties properties) {
  44. GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
  45. genericObjectPoolConfig.setMaxIdle(properties.getMaxIdle());
  46. genericObjectPoolConfig.setMinIdle(properties.getMinIdle());
  47. genericObjectPoolConfig.setMaxTotal(properties.getMaxTotal());
  48. genericObjectPoolConfig.setMaxWaitMillis(properties.getMaxWait());
  49. return genericObjectPoolConfig;
  50. }
  51. }

3.6 自定义 spring.factories 文件

        模仿框架的定义方式, 在 resource 下创建一个 META-INF 包, 并创建 spring.factories 文件

  1. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  2. com.kone.sp.common.redis2.config.RedissonAutoConfiguration,\
  3. com.kone.sp.common.redis2.config.RedisCacheAutoConfiguration,\
  4. com.kone.sp.common.redis2.config.RedisTemplateAutoConfiguration,\
  5. com.kone.sp.common.redis2.config.LettuceConnectionAutoConfiguration

3.7 在其他模块测试自定义的starter

        对我们的自定义 redis-starter 使用 install 命令, 之后在 maven 仓库里可以看到

在 pom 文件中引入, 并在其他模块的 yml 文件中配置 RedisTemplateConfigProperties 需要的配置参数, 这里要注意前缀和属性名称要和配置类对应上

        之后从配置文件中可以看到, 我们在其他模块编写的 yml 配置, 已经在创建连接工厂的时候被读取到 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/785951
推荐阅读
相关标签
  

闽ICP备14008679号