单数据源版

1.引入依赖

  1. <!--Web组件-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <!--Redis-->
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-data-redis</artifactId>
  10. </dependency>
  11. <!--Redis连接池-->
  12. <dependency>
  13. <groupId>org.apache.commons</groupId>
  14. <artifactId>commons-pool2</artifactId>
  15. <version>2.9.0</version>
  16. </dependency>

2.yml文件增加配置

  1. #Spring配 置
  2. spring:
  3. #Redis配置
  4. redis:
  5. host: 8.142.132.135
  6. port: 6379
  7. password:
  8. database: 0
  9. jedis:
  10. pool:
  11. max-active: 150
  12. max-wait: 100
  13. max-idle: 100
  14. min-idle: 50
  15. timeout: 5000ms
  1. max-active:最大激活连接数
  2. max-wait:连接最大等待时间
  3. max-idle:最大空闲连接数量
  4. min-idle:最小空闲连接数

    3.增加配置类

    ```java import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

/**

  • @author 冯铁城 [17615007230@163.com]
  • @date 2022-05-06 16:18:18
  • @describe: Redis配置类 */ @Configuration public class RedisConfig {

    @Bean @ConditionalOnMissingBean(name = “redisTemplate”) public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {

    1. //1.创建序列化类
    2. Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
    3. ObjectMapper om = new ObjectMapper();
    4. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    5. jackson2JsonRedisSerializer.setObjectMapper(om);
    6. //2.设置序列化规则
    7. RedisTemplate<String, Object> template = new RedisTemplate<>();
    8. template.setConnectionFactory(redisConnectionFactory);
    9. template.setKeySerializer(jackson2JsonRedisSerializer);
    10. template.setValueSerializer(jackson2JsonRedisSerializer);
    11. template.setHashKeySerializer(jackson2JsonRedisSerializer);
    12. template.setHashValueSerializer(jackson2JsonRedisSerializer);
    13. template.afterPropertiesSet();
    14. //3.返回模板
    15. return template;

    } } ```

    4.编写单元测试验证

    ```java import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest class RedistryApplicationTests {

  1. @Autowired
  2. private RedisTemplate<String, Object> redisTemplate;
  3. @Test
  4. void testRedis() {
  5. redisTemplate.opsForValue().set("key", "value");
  6. Object key = redisTemplate.opsForValue().get("key");
  7. Assert.assertNotNull(key);
  8. Assert.assertEquals("value", key);
  9. }

}

  1. <a name="EH8UY"></a>
  2. ## 多数据源版
  3. <a name="TTfJR"></a>
  4. ### 1.引入依赖
  5. ```xml
  6. <!--Web组件-->
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-web</artifactId>
  10. </dependency>
  11. <!--Redis-->
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-data-redis</artifactId>
  15. </dependency>
  16. <!--Redis连接池-->
  17. <dependency>
  18. <groupId>org.apache.commons</groupId>
  19. <artifactId>commons-pool2</artifactId>
  20. <version>2.9.0</version>
  21. </dependency>

2.yml文件增加配置

  1. #配置Redis数据源(支持多数据源)
  2. redis:
  3. #默认Redis连接
  4. default-redis:
  5. host: 8.142.132.135
  6. port: 6379
  7. password:
  8. database: 0
  9. timeout: 6000
  10. max-active: 150
  11. max-wait: 100
  12. max-idle: 100
  13. min-idle: 50
  14. #其他Redis连接
  15. other-redis:
  16. host: 8.142.132.135
  17. port: 6379
  18. password:
  19. database: 1
  20. timeout: 6000
  21. max-active: 150
  22. max-wait: 100
  23. max-idle: 100
  24. min-idle: 50

3.添加Redis配置接口

  1. /**
  2. * @author 冯铁城 [fengtiecheng@cyou-inc.com]
  3. * @date 2022-01-07 16:53:28
  4. * @describe:
  5. */
  6. public interface RedisConfig {
  7. /**
  8. * 获取主机信息
  9. *
  10. * @return
  11. */
  12. String getHost();
  13. /**
  14. * 获取端口
  15. *
  16. * @return
  17. */
  18. int getPort();
  19. /**
  20. * 获取密码
  21. *
  22. * @return
  23. */
  24. String getPassword();
  25. /**
  26. * 获取数据库信息
  27. *
  28. * @return
  29. */
  30. int getDatabase();
  31. /**
  32. * 获取连接超时时间
  33. *
  34. * @return
  35. */
  36. long getTimeOut();
  37. /**
  38. * 获取最大激活连接数
  39. *
  40. * @return
  41. */
  42. int getMaxActive();
  43. /**
  44. * 获取最大等待时间
  45. *
  46. * @return
  47. */
  48. int getMaxWait();
  49. /**
  50. * 获取最大等待连接中的数量
  51. *
  52. * @return
  53. */
  54. int getMaxIdle();
  55. /**
  56. * 获取最小等待连接中的数量
  57. *
  58. * @return
  59. */
  60. int getMinIdle();
  61. }

4.添加Redis配置实现类

  1. import lombok.Setter;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.stereotype.Component;
  4. /**
  5. * @author 冯铁城 [fengtiecheng@cyou-inc.com]
  6. * @date 2022-01-07 16:59:24
  7. * @describe: 平台默认Redis配置
  8. */
  9. @Component
  10. @ConfigurationProperties(prefix = "redis.default-redis")
  11. @Setter
  12. public class DefaultRedisConfig implements RedisConfig {
  13. /**
  14. * 主机信息
  15. */
  16. private String host;
  17. /**
  18. * 端口
  19. */
  20. private int port;
  21. /**
  22. * 密码
  23. */
  24. private String password;
  25. /**
  26. * 数据库
  27. */
  28. private int database;
  29. /**
  30. * 连接超时时间
  31. */
  32. private long timeOut;
  33. /**
  34. * 最大激活连接数
  35. */
  36. private int maxActive;
  37. /**
  38. * 最大等待时间
  39. */
  40. private int maxWait;
  41. /**
  42. * 最大等待连接中的数量
  43. */
  44. private int maxIdle;
  45. /**
  46. * 最小等待连接中的数量
  47. */
  48. private int minIdle;
  49. @Override
  50. public String getHost() {
  51. return this.host;
  52. }
  53. @Override
  54. public int getPort() {
  55. return this.port;
  56. }
  57. @Override
  58. public String getPassword() {
  59. return this.password;
  60. }
  61. @Override
  62. public int getDatabase() {
  63. return this.database;
  64. }
  65. @Override
  66. public long getTimeOut() {
  67. return this.timeOut;
  68. }
  69. @Override
  70. public int getMaxActive() {
  71. return this.maxActive;
  72. }
  73. @Override
  74. public int getMaxWait() {
  75. return this.maxWait;
  76. }
  77. @Override
  78. public int getMaxIdle() {
  79. return this.maxIdle;
  80. }
  81. @Override
  82. public int getMinIdle() {
  83. return this.minIdle;
  84. }
  85. }
  1. import lombok.Setter;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.stereotype.Component;
  4. /**
  5. * @author 冯铁城 [fengtiecheng@cyou-inc.com]
  6. * @date 2022-01-07 16:59:24
  7. * @describe: 其他Redis配置
  8. */
  9. @Component
  10. @ConfigurationProperties(prefix = "redis.other-redis")
  11. @Setter
  12. public class OtherRedisConfig implements RedisConfig {
  13. /**
  14. * 主机信息
  15. */
  16. private String host;
  17. /**
  18. * 端口
  19. */
  20. private int port;
  21. /**
  22. * 密码
  23. */
  24. private String password;
  25. /**
  26. * 数据库
  27. */
  28. private int database;
  29. /**
  30. * 连接超时时间
  31. */
  32. private long timeOut;
  33. /**
  34. * 最大激活连接数
  35. */
  36. private int maxActive;
  37. /**
  38. * 最大等待时间
  39. */
  40. private int maxWait;
  41. /**
  42. * 最大等待连接中的数量
  43. */
  44. private int maxIdle;
  45. /**
  46. * 最小等待连接中的数量
  47. */
  48. private int minIdle;
  49. @Override
  50. public String getHost() {
  51. return this.host;
  52. }
  53. @Override
  54. public int getPort() {
  55. return this.port;
  56. }
  57. @Override
  58. public String getPassword() {
  59. return this.password;
  60. }
  61. @Override
  62. public int getDatabase() {
  63. return this.database;
  64. }
  65. @Override
  66. public long getTimeOut() {
  67. return this.timeOut;
  68. }
  69. @Override
  70. public int getMaxActive() {
  71. return this.maxActive;
  72. }
  73. @Override
  74. public int getMaxWait() {
  75. return this.maxWait;
  76. }
  77. @Override
  78. public int getMaxIdle() {
  79. return this.maxIdle;
  80. }
  81. @Override
  82. public int getMinIdle() {
  83. return this.minIdle;
  84. }
  85. }

5.添加Redis连接生成工厂

  1. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  2. import com.fasterxml.jackson.annotation.PropertyAccessor;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.context.annotation.Primary;
  10. import org.springframework.data.redis.connection.RedisConnectionFactory;
  11. import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
  12. import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
  13. import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
  14. import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
  15. import org.springframework.data.redis.core.RedisTemplate;
  16. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  17. import org.springframework.data.redis.serializer.StringRedisSerializer;
  18. import java.time.Duration;
  19. /**
  20. * @author 冯铁城 [fengtiecheng@cyou-inc.com]
  21. * @date 2022-01-07 17:33:43
  22. * @describe: 多数据源Redis工厂
  23. */
  24. @Configuration
  25. public class RedisTemplateConstructor {
  26. @Autowired
  27. @Qualifier("defaultRedisConfig")
  28. private RedisConfig defaultRedisConfig;
  29. @Autowired
  30. @Qualifier("otherRedisConfig")
  31. private RedisConfig otherRedisConfig;
  32. /**
  33. * 创建默认RedisTemplate
  34. *
  35. * @return 默认RedisTemplate
  36. */
  37. @Bean(name = "defaultRedis")
  38. @Primary
  39. public RedisTemplate<String, Object> defaultRedisTemplate() {
  40. //1.创建连接工厂
  41. LettuceConnectionFactory connectionFactory = this.lettuceConnectionFactory(defaultRedisConfig);
  42. //2.创建RedisTemplate返回
  43. return this.createRedisTemplate(connectionFactory);
  44. }
  45. /**
  46. * 创建其他RedisTemplate
  47. *
  48. * @return 默认RedisTemplate
  49. */
  50. @Bean(name = "otherRedis")
  51. public RedisTemplate<String, Object> otherRedisTemplate() {
  52. //1.创建连接工厂
  53. LettuceConnectionFactory connectionFactory = this.lettuceConnectionFactory(otherRedisConfig);
  54. //2.创建RedisTemplate返回
  55. return this.createRedisTemplate(connectionFactory);
  56. }
  57. /**
  58. * 创建lettuce连接池工厂
  59. *
  60. * @param redisConfig Redis配置
  61. * @return lettuce 连接池工厂
  62. */
  63. private LettuceConnectionFactory lettuceConnectionFactory(RedisConfig redisConfig) {
  64. //1.线程池设置
  65. GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
  66. poolConfig.setMaxTotal(redisConfig.getMaxActive());
  67. poolConfig.setMaxWaitMillis(redisConfig.getMaxWait());
  68. poolConfig.setMaxIdle(redisConfig.getMaxIdle());
  69. poolConfig.setMinIdle(redisConfig.getMinIdle());
  70. //2.线程池客户端设置
  71. LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration
  72. .builder()
  73. .commandTimeout(Duration.ofSeconds(redisConfig.getTimeOut()))
  74. .poolConfig(poolConfig)
  75. .build();
  76. //3.Redis基础设置
  77. RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
  78. configuration.setHostName(redisConfig.getHost());
  79. configuration.setDatabase(redisConfig.getDatabase());
  80. configuration.setPassword(redisConfig.getPassword());
  81. configuration.setPort(redisConfig.getPort());
  82. //4.返回连接池工厂
  83. LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(configuration, clientConfiguration);
  84. lettuceConnectionFactory.setShareNativeConnection(true);
  85. lettuceConnectionFactory.afterPropertiesSet();
  86. return lettuceConnectionFactory;
  87. }
  88. /**
  89. * 创建RedisTemplate并设置序列化规则
  90. *
  91. * @param redisConnectionFactory redis连接池
  92. */
  93. private RedisTemplate<String, Object> createRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
  94. //1.创建Redis连接模板
  95. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  96. //2.设置连接工厂
  97. redisTemplate.setConnectionFactory(redisConnectionFactory);
  98. //3.设置keyValue序列化规则
  99. redisTemplate.setKeySerializer(new StringRedisSerializer());
  100. redisTemplate.setValueSerializer(new StringRedisSerializer());
  101. //4.创建Hash序列化规则
  102. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  103. ObjectMapper om = new ObjectMapper();
  104. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  105. jackson2JsonRedisSerializer.setObjectMapper(om);
  106. //5.设置HashKeyValue序列化规则
  107. redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
  108. redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
  109. //6.返回
  110. redisTemplate.afterPropertiesSet();
  111. return redisTemplate;
  112. }
  113. }

6.编写单元测试验证

  1. import org.junit.Assert;
  2. import org.junit.jupiter.api.Test;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Qualifier;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. @SpringBootTest
  8. class RedistryApplicationTests {
  9. @Autowired
  10. @Qualifier("defaultRedis")
  11. private RedisTemplate<String, Object> defaultRedis;
  12. @Autowired
  13. @Qualifier("otherRedis")
  14. private RedisTemplate<String, Object> otherRedis;
  15. @Test
  16. void testRedis() {
  17. defaultRedis.opsForValue().set("defaultKey", "defaultValue");
  18. Object defaultKey = defaultRedis.opsForValue().get("defaultKey");
  19. Assert.assertNotNull(defaultKey);
  20. Assert.assertEquals("defaultValue", defaultKey);
  21. otherRedis.opsForValue().set("otherKey", "otherValue");
  22. Object otherKey = otherRedis.opsForValue().get("otherKey");
  23. Assert.assertNotNull(otherKey);
  24. Assert.assertEquals("otherValue", otherKey);
  25. }
  26. }