前置知识储备
- (一)自定义 BeanDefinition
- (二)自定义 BeanDefinitionRegistryPostProcessor
- (三)自定义 AutowireCandidateResolver
Maven 依赖
pom.xml
添加如下依赖:
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.16.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
(一)Redissson 简单使用
1)初始化 RedissonClient
public static RedissonClient redissonClient() {
// 1. Create config object
Config config = new Config();
config.useSingleServer().setAddress("redis://host:6379");
// 2. Create Redisson instance
// Sync and Async API
RedissonClient redisson = Redisson.create(config);
return redisson;
}
2)测试代码
@Slf4j
public class RedisssonTest {
public static void main(String[] args) {
RedissonClient redissonClient = redissonClient();
RBucket<String> bucket = redissonClient.getBucket("key");
bucket.delete();
log.info("value: {}", bucket.get());
bucket.set("value");
log.info("value: {}", bucket.get());
}
}
3)控制台输出:
16:26:36.081 [main] INFO com.example.springdemo.RedisssonTest - value: null
16:26:36.161 [main] INFO com.example.springdemo.RedisssonTest - value: value
(二)动态注入 RedisBean
实现
1)定义 redissonClient
,并进行相关配置
@Configuration
public class RedisConfig {
@Bean
public static RedissonClient redissonClient() {
// 1. Create config object
Config config = new Config();
config.useSingleServer().setAddress("redis://host:6379");
// 2. Create Redisson instance
// Sync and Async API
RedissonClient redisson = Redisson.create(config);
return redisson;
}
}
2)定义 RedissonBean
注解。
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface RedissonBean {
String key();
}
@Target({ElementType.FIELD})
表示此注解只能作用在字段上。
3)通过自定义 BeanDefinitionRegistryPostProcessor
动态注册 RedisBean
。
@Slf4j
@Component
public class RedisssonBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
@SneakyThrows
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
for (String beanName : registry.getBeanDefinitionNames()) {
BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
if (beanDefinition.getBeanClassName() == null) {
continue;
}
if (beanDefinition.getBeanClassName().startsWith("com.example.springdemo")) {
Class<?> beanClass = Class.forName(beanDefinition.getBeanClassName());
FieldUtils.getFieldsListWithAnnotation(beanClass, RedissonBean.class)
.forEach(field -> createBeanDefinition(registry, field));
}
}
}
private void createBeanDefinition(BeanDefinitionRegistry registry, Field field) {
// 1. 实例化一个 RootBeanDefinition
RootBeanDefinition beanDefinition = new RootBeanDefinition();
// 2. 设置 FactoryBeanName 和 FactoryMethodName
beanDefinition.setFactoryBeanName("redissonClient");
String factoryMethodName = getFactoryMethodName(field);
log.info("factoryMethodName: {}", factoryMethodName);
beanDefinition.setFactoryMethodName(factoryMethodName);
// 3. 设置 FactoryMethodName 的参数
ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues();
String redisKey = getRedisKey(field);
log.info("redisKey: {}", redisKey);
constructorArgumentValues.addGenericArgumentValue(redisKey);
beanDefinition.setConstructorArgumentValues(constructorArgumentValues);
// 4. 注册到 Spring 容器中
registry.registerBeanDefinition(redisKey, beanDefinition);
}
private String getFactoryMethodName(Field field) {
String typeName = field.getType().getSimpleName();
return "get" + typeName.substring(1);
}
private String getRedisKey(Field field) {
RedissonBean annotation = field.getAnnotation(RedissonBean.class);
return annotation.key();
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
// do nothing
}
}
4)自定义 RedissonContextAnnotationAutowireCandidateResolver
,用来和第 3 步动态注册的 RedissBean
进行匹配。
@Slf4j
public class RedissonContextAnnotationAutowireCandidateResolver extends ContextAnnotationAutowireCandidateResolver {
@Override
public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
boolean match = super.isAutowireCandidate(bdHolder, descriptor);
if (descriptor.getDependencyType().getName().startsWith("org.redisson.api")) {
MethodParameter methodParameter = descriptor.getMethodParameter();
// 1. 通过方法参数名称找到对应的字段
Field field = FieldUtils.getField(methodParameter.getDeclaringClass(), methodParameter.getParameterName(), true);
// 2. 获取字段上的 RedissonBean 注解
RedissonBean annotation = field.getAnnotation(RedissonBean.class);
// 3. 如果存在注解,且注解的的 key 和 beanName 匹配,则返回 true
if (annotation != null && annotation.key().equals(bdHolder.getBeanName())) {
match = true;
}
// 4. 打印一些调试信息
log.info("");
log.info("[isAutowireCandidate] [descriptor] dependencyName:{}, dependencyType:{}", descriptor.getDependencyName(), descriptor.getDependencyType());
log.info("[isAutowireCandidate] [bdHolder] beanName:{}", bdHolder.getBeanName());
log.info("[isAutowireCandidate] [RedissonBean] key:{}", annotation.key());
log.info("[isAutowireCandidate]match:{}", match);
log.info("");
}
return match;
}
@Override
public boolean isRequired(DependencyDescriptor descriptor) {
return super.isRequired(descriptor);
}
}
5)自定义 ApplicationContextInitializer
替换 Spring 默认的 ContextAnnotationAutowireCandidateResolver
。
package com.example.springdemo.registry;
@Slf4j
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
log.info("-----MyApplicationContextInitializer initialize-----");
if (applicationContext.getBeanFactory() instanceof DefaultListableBeanFactory) {
DefaultListableBeanFactory bf = (DefaultListableBeanFactory) applicationContext.getBeanFactory();
bf.setAutowireCandidateResolver(new RedissonContextAnnotationAutowireCandidateResolver());
} else {
throw new IllegalStateException("错误的 BeanFactory");
}
}
}
并在 META-INF/spring.factories
中配置:
org.springframework.context.ApplicationContextInitializer=com.example.springdemo.registry.MyApplicationContextInitializer
6)在 DemoService
中使用 @RedissonBean
注解进行测试。
@Slf4j
@Service
@RequiredArgsConstructor
public class DemoService {
@RedissonBean(key = "redis1")
private final RList<Long> list1;
@RedissonBean(key = "redis2")
private final RList<Long> list2;
public void handle() {
handleList1();
handleList2();
}
public void clean() {
list1.clear();
list2.clear();
}
private void handleList1() {
log.info("list1:{} ", list1.readAll());
list1.add(1L);
list1.add(2L);
list1.add(3L);
log.info("list1:{} ", list1.readAll());
}
private void handleList2() {
log.info("list2:{} ", list2.readAll());
list2.add(4L);
list2.add(5L);
list2.add(6L);
log.info("list2:{} ", list2.readAll());
}
}
7)测试代码:
@Slf4j
@SpringBootApplication
public class SpringDemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(SpringDemoApplication.class, args);
DemoService demoService = context.getBean(DemoService.class);
demoService.clean();
demoService.handle();
}
}
控制台输出:
2021-07-09 15:38:27.461 INFO 23108 --- [ main] c.e.springdemo.service.DemoService : list1:[]
2021-07-09 15:38:27.510 INFO 23108 --- [ main] c.e.springdemo.service.DemoService : list1:[1, 2, 3]
2021-07-09 15:38:27.518 INFO 23108 --- [ main] c.e.springdemo.service.DemoService : list2:[]
2021-07-09 15:38:27.653 INFO 23108 --- [ main] c.e.springdemo.service.DemoService : list2:[4, 5, 6]
参考
- https://github.com/redisson/redisson
- 单 Redis 节点模式