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