须要用到的组件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
<version>2.6.2</version>
</dependency>
yml 配置:
spring:
redis:
host: 127.0.0.1
port: 6379
这外面有两个主动加载的 bean 须要关注:
翻看代码:LettuceConnectionConfiguration.java,
@Bean
@ConditionalOnMissingBean(RedisConnectionFactory.class)
LettuceConnectionFactory redisConnectionFactory(
ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers,
ClientResources clientResources) {
LettuceClientConfiguration clientConfig = getLettuceClientConfiguration(builderCustomizers, clientResources,
getProperties().getLettuce().getPool());
return createLettuceConnectionFactory(clientConfig);
}
因为在上述代码中有参数须要,@ConditionalOnMissingBean(RedisConnectionFactory.class) 作用便产生了。
再看 RedisReactiveAutoConfiguration.java
@Bean
@ConditionalOnMissingBean(name = "reactiveRedisTemplate")
@ConditionalOnBean(ReactiveRedisConnectionFactory.class)
public ReactiveRedisTemplate<Object, Object> reactiveRedisTemplate(ReactiveRedisConnectionFactory reactiveRedisConnectionFactory, ResourceLoader resourceLoader) {
JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer(resourceLoader.getClassLoader());
RedisSerializationContext<Object, Object> serializationContext = RedisSerializationContext
.newSerializationContext().key(jdkSerializer).value(jdkSerializer).hashKey(jdkSerializer)
.hashValue(jdkSerializer).build();
return new ReactiveRedisTemplate<>(reactiveRedisConnectionFactory, serializationContext);
}
所以呢,应用的时候,能够间接应用
@Autowired
ReactiveStringRedisTemplate abc;
@GetMapping("/redis")
public Mono<Boolean> redis() {ReactiveValueOperations<String, String> ops = abc.opsForValue();
return ops.set("test", "black");
}
或者还有一种形式:
@Bean
ReactiveStringRedisTemplate reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {return new ReactiveStringRedisTemplate(factory);
}
@Autowired
ReactiveStringRedisTemplate reactiveRedisTemplate;
留神这里变量名字最好是 reactiveRedisTemplate,不然就会报错
Field abc in xxx required a single bean, but 2 were found:
- reactiveRedisTemplate: defined by method 'reactiveRedisTemplate' in com.example.WebfluxApplication
- reactiveStringRedisTemplate: defined by method 'reactiveStringRedisTemplate' in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.class]