Spring Cloud自定义stater整合redis(七)

580 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第19天,点击查看活动详情

前言

Redis常用的客户端有JedisLettuceRedisson。Spring Boot对Redis的操作主要封装在spring-boot-starter-data-redis依赖中,在2.X的版本中采用的是Lettuce客户端,因为Redisson提供了分布式锁、队列、限流等特性,所以选择它作为 Spring Data Redis 的客户端,本次整合Redis不直接在业务模块中进行整合,单独抽取一个自己的stater进行redis的封装,然后在其他业务模块中引入自定义的stater。这样能做到很好的业务分离,便于后期的维护。

考虑到有的项目中可能使用Spring cache注解进行缓存,所以在stater中同样也进行了Spring cache的配置。

依赖引入

vip-cloudpom.xml

<redisson.version>3.17.3</redisson.version>

<dependency>
  <groupId>org.redisson</groupId>
  <artifactId>redisson-spring-boot-starter</artifactId>
  <version>${redisson.version}</version>
</dependency>

stater模块创建

vip-framework下创建modulevip-spring-boot-stater-redis创建过程,可参看第一篇的微服务搭建。

引入依赖

vip-spring-boot-stater-redispom.xml

<dependency>
  <groupId>com.vip</groupId>
  <artifactId>vip-calculate-common</artifactId>
  <version>1.0-SNAPSHOT</version>
</dependency>


<dependency>
  <groupId>org.redisson</groupId>
  <artifactId>redisson-spring-boot-starter</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId> 
</dependency>

redis配置类

  • 创建包名com.vip.framework.redis.config

  • 创建redis的配置类 VipRedisAutoConfiguration

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * Redis 配置类
 */
@Configuration
public class VipRedisAutoConfiguration {

    /**
     * 创建 RedisTemplate Bean,使用 JSON 序列化方式
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // 创建 RedisTemplate 对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 设置 RedisConnection 工厂。😈 它就是实现多种 Java Redis 客户端接入的秘密工厂。感兴趣的胖友,可以自己去撸下。
        template.setConnectionFactory(factory);
        // 使用 String 序列化方式,序列化 KEY 。
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        // 使用 JSON 序列化方式(库是 Jackson ),序列化 VALUE 。
        template.setValueSerializer(RedisSerializer.json());
        template.setHashValueSerializer(RedisSerializer.json());
        return template;
    }

}

VipCacheAutoConfiguration

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
@EnableCaching
public class VipCacheAutoConfiguration {
    /**
     * RedisCacheConfiguration Bean
     *
     * 参考 org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration 的 createConfiguration 方法
     */
    @Bean
    @Primary
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        // 设置使用 JSON 序列化方式
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));

        // 设置 CacheProperties.Redis 的属性
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config.prefixKeysWith(redisProperties.getKeyPrefix());
            // config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}

添加配置

/META_INF/spring.factories配置,如果没有相应的目录和文件,需要手动创建。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.vip.framework.redis.config.VipRedisAutoConfiguration,\
  com.vip.framework.redis.config.VipCacheAutoConfiguration

org.springframework.boot.autoconfigure.EnableAutoConfiguration是固定的key。value是自己的配置类的全限定类名。

业务模块整合

  • 引入依赖 业务模块整合自定义的stater-redis。在vip-calculate-bizpom.xml中引入依赖。引入后记得刷新Maven
<dependency>
  <groupId>com.vip</groupId>
  <artifactId>vip-spring-boot-stater-redis</artifactId>
  <version>1.0-SNAPSHOT</version>
</dependency>
  • 修改配置文件 修改配置文件

application.properties

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.database=0
  • 添加测试类RedisController
@Slf4j
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/test")
    public CommonResult redisTest() {
        CatMainX catMainX = new CatMainX();
        catMainX.setAreaCode("123");
        catMainX.setAreaFlag("1");
        redisTemplate.opsForValue().set("calculate", catMainX);

        CatMainX calculate = (CatMainX) redisTemplate.opsForValue().get("calculate");
        log.info("redisTest() returned: " + calculate);
        return success(calculate);
    }
}
  • 功能测试

调用接口,查看redis,redis中正常保存数据,且对象的保存格式为json字符串。