reactive方式读写redis

需要用到的组件:

    
      org.springframework.boot
      spring-boot-starter-data-redis-reactive
      2.6.2
    

yml配置:

spring:
    redis:
        host: 127.0.0.1
        port: 6379

这里面有两个自动加载的bean需要关注:
翻看代码:LettuceConnectionConfiguration.java,

    @Bean
    @ConditionalOnMissingBean(RedisConnectionFactory.class)
    LettuceConnectionFactory redisConnectionFactory(
            ObjectProvider 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 reactiveRedisTemplate(
            ReactiveRedisConnectionFactory reactiveRedisConnectionFactory, ResourceLoader resourceLoader) {
        JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer(
                resourceLoader.getClassLoader());
        RedisSerializationContext serializationContext = RedisSerializationContext
                .newSerializationContext().key(jdkSerializer).value(jdkSerializer).hashKey(jdkSerializer)
                .hashValue(jdkSerializer).build();
        return new ReactiveRedisTemplate<>(reactiveRedisConnectionFactory, serializationContext);
    }

所以呢 ,使用的时候, 可以直接使用

    @Autowired
    ReactiveStringRedisTemplate abc;

    @GetMapping("/redis")
    public Mono redis() {
        ReactiveValueOperations  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]

你可能感兴趣的:(java)