chenjiahe
2022-06-28 09b4c6896acdbfa6d5c0c0c5c24bfc17d6ee2bf3
提交 | 用户 | age
09b4c6 1 package com.hx.redisson.register;
a0ad14 2
C 3 import com.fasterxml.jackson.annotation.JsonAutoDetect;
4 import com.fasterxml.jackson.annotation.PropertyAccessor;
5 import com.fasterxml.jackson.databind.ObjectMapper;
6 import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
09b4c6 7 import com.hx.redisson.entity.RedissondbConfigEntity;
a0ad14 8 import org.apache.commons.collections.CollectionUtils;
C 9 import org.redisson.Redisson;
10 import org.redisson.api.RedissonClient;
11 import org.redisson.client.codec.StringCodec;
12 import org.redisson.config.Config;
13 import org.redisson.config.SingleServerConfig;
14 import org.redisson.spring.data.connection.RedissonConnectionFactory;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
17 import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
18 import org.springframework.beans.factory.support.BeanDefinitionRegistry;
19 import org.springframework.beans.factory.support.GenericBeanDefinition;
20 import org.springframework.boot.context.properties.bind.Binder;
21 import org.springframework.context.EnvironmentAware;
22 import org.springframework.context.annotation.Configuration;
23 import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
24 import org.springframework.core.env.Environment;
25 import org.springframework.core.type.AnnotationMetadata;
26 import org.springframework.data.redis.connection.RedisConnectionFactory;
27 import org.springframework.data.redis.core.RedisTemplate;
28 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
29 import org.springframework.data.redis.serializer.RedisSerializer;
30 import org.springframework.data.redis.serializer.StringRedisSerializer;
31
32 import java.util.List;
33
34 /**
35  * <h1>redistemplate初始化</h1>
36  * <p>
37  * 作用:
38  * <p>
39  * 读取系统配置,系统启动时,读取redis 的配置,初始化所有的redistemplate
40  * 并动态注册为bean
41  *
42  * @author gengzi
43  * @date 2021年1月5日22:16:29
44  */
45 @Configuration
46 public class RedisRegister implements EnvironmentAware, ImportBeanDefinitionRegistrar {
47
48     private Logger logger = LoggerFactory.getLogger(RedisRegister.class);
49
50     /**用于获取环境配置*/
51     private Environment environment;
52     /**用于绑定对象*/
53     private Binder binder;
54
55     /**
56      * 设置环境
57      *
58      * @param environment
59      */
60     @Override
61     public void setEnvironment(Environment environment) {
62         this.environment = environment;
63         this.binder = Binder.get(environment);
64     }
65
66     /**
67      * 注册bean
68      *
69      * @param importingClassMetadata
70      * @param registry
71      */
72     @Override
73     public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
74         logger.info("《《《动态注册bean开始》》》");
75         RedissondbConfigEntity redissondb;
76         try {
77             redissondb = binder.bind("redissondb", RedissondbConfigEntity.class).get();
78         } catch (Exception e) {
79             logger.error("读取redissondb环境配置失败", e);
80             return;
81         }
82         List<Integer> databases = redissondb.getDatabases();
83         if (CollectionUtils.isNotEmpty(databases)) {
84             databases.forEach(db -> {
85                 // 单机模式,集群只能使用db0
86                 Config config = new Config();
87                 config.setCodec(StringCodec.INSTANCE);
88                 SingleServerConfig singleConfig = config.useSingleServer();
89                 singleConfig.setAddress("redis://"+redissondb.getHost()+":"+redissondb.getPort());
90                 singleConfig.setPassword(redissondb.getPassword());
91                 singleConfig.setDatabase(db);
92
93                 System.out.println("getHost:"+singleConfig.getAddress());
94                 System.out.println("getHost:"+singleConfig.getPassword());
95                 RedissonClient redissonClient = Redisson.create(config);
96                 // 构造RedissonConnectionFactory
97                 RedissonConnectionFactory redisConnectionFactory = new RedissonConnectionFactory(redissonClient);
98                 // bean定义
99                 GenericBeanDefinition redisTemplate = new GenericBeanDefinition();
100                 // 设置bean 的类型
101                 redisTemplate.setBeanClass(RedisTemplate.class);
102                 // 设置自动注入的形式,根据名称
103                 redisTemplate.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_NAME);
104                 // redisTemplate 的属性配置
105                 redisTemplate(redisTemplate, redisConnectionFactory);
106                 // 注册Bean
107                 registry.registerBeanDefinition("redisTemplate" + db, redisTemplate);
108             });
109         }
110         logger.info("《《《动态注册bean结束》》》");
111
112     }
113
114     /**
115      * redisTemplate 的属性配置
116      *
117      * @param redisTemplate          泛型bean
118      * @param redisConnectionFactory 连接工厂
119      * @return
120      */
121     public GenericBeanDefinition redisTemplate(GenericBeanDefinition redisTemplate, RedisConnectionFactory redisConnectionFactory) {
122         RedisSerializer<String> stringRedisSerializer = new StringRedisSerializer();
123         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
124         // 解决查询缓存转换异常的问题
125         ObjectMapper om = new ObjectMapper();
126         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
127         om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
128                 ObjectMapper.DefaultTyping.NON_FINAL);
129         jackson2JsonRedisSerializer.setObjectMapper(om);
130         // key采用String的序列化方式,value采用json序列化方式
131         // 通过方法设置属性值
132         redisTemplate.getPropertyValues().add("connectionFactory", redisConnectionFactory);
133         redisTemplate.getPropertyValues().add("keySerializer", stringRedisSerializer);
134         redisTemplate.getPropertyValues().add("hashKeySerializer", stringRedisSerializer);
135         redisTemplate.getPropertyValues().add("valueSerializer", jackson2JsonRedisSerializer);
136         redisTemplate.getPropertyValues().add("hashValueSerializer", jackson2JsonRedisSerializer);
137
138         return redisTemplate;
139     }
140 }
141