springboot集成redis 并且配置文件加密访问

加入maven依赖

  <!-- 缓存依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <scope>compile</scope>
        </dependency>

配置文件配置

# redis数据源
spring:
  redis:
    host: test01
    database: 1
    password: eGlud2VpMjAyMA==
    servlet:
      multipart:
        max-file-size: 100MB
        max-request-size: 100MB
    port: 6380     

代码实现(利用spring面向切面实现加密密码连接)

step1: 创建一个切面获取redis 的登录密码

public class CommonPointCut {

    @Pointcut("execution(* org.springframework.boot.autoconfigure.data.redis.RedisProperties.getPassword())")
    public void getRedisConnectionPwd(){}
}    

step2:加入config配置文件

@Data
@Aspect
@Configuration
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConfig {

    private static final Logger log = LoggerFactory.getLogger(RedisConfig.class);

    @Autowired
    private RedisProperties redisProperties;

    private String password;

    @Before("com.xinwei.shop.pointcut.CommonPointCut.getRedisConnectionPwd()")
    public void setRedisProperties(){
        log.info("login redis to decode password of project");
        String pwdStr =  Base64.decodeStr(password);
        log.info("redis login password = {}", pwdStr);
        redisProperties.setPassword(pwdStr);
    }

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        //设置自定义的序列化方式(fastjson) ,不然key会出现 \xac\xed\x00\x05t\x00\tb
        template.setDefaultSerializer(new FastJsonRedisSerializer(Object.class));
        template.setKeySerializer(new StringRedisSerializer());
        return template;
    }

}

完成


版权声明:本文为fanghuainihao原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。