前置知識(shí)儲(chǔ)備
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)測(cè)試代碼
@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)控制臺(tái)輸出:
16:26:36.081 [main] INFO com.example.springdemo.RedisssonTest - value: null
16:26:36.161 [main] INFO com.example.springdemo.RedisssonTest - value: value
(二)動(dòng)態(tài)注入 RedisBean
實(shí)現(xiàn)
1)定義 redissonClient
,并進(jìn)行相關(guān)配置
@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
動(dòng)態(tài)注冊(cè) 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. 實(shí)例化一個(gè) RootBeanDefinition
RootBeanDefinition beanDefinition = new RootBeanDefinition();
// 2. 設(shè)置 FactoryBeanName 和 FactoryMethodName
beanDefinition.setFactoryBeanName("redissonClient");
String factoryMethodName = getFactoryMethodName(field);
log.info("factoryMethodName: {}", factoryMethodName);
beanDefinition.setFactoryMethodName(factoryMethodName);
// 3. 設(shè)置 FactoryMethodName 的參數(shù)
ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues();
String redisKey = getRedisKey(field);
log.info("redisKey: {}", redisKey);
constructorArgumentValues.addGenericArgumentValue(redisKey);
beanDefinition.setConstructorArgumentValues(constructorArgumentValues);
// 4. 注冊(cè)到 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 步動(dòng)態(tài)注冊(cè)的 RedissBean
進(jìn)行匹配。
@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. 通過方法參數(shù)名稱找到對(duì)應(yīng)的字段
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. 打印一些調(diào)試信息
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 默認(rèn)的 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("錯(cuò)誤的 BeanFactory");
}
}
}
并在 META-INF/spring.factories
中配置:
org.springframework.context.ApplicationContextInitializer=com.example.springdemo.registry.MyApplicationContextInitializer
6)在 DemoService
中使用 @RedissonBean
注解進(jìn)行測(cè)試撩幽。
@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)測(cè)試代碼:
@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();
}
}
控制臺(tái)輸出:
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]