Redis密码在springboot中自定义加解密实践

 更新时间:2026年01月12日 09:30:56   作者:MartinYangHJ  
文章介绍了在Spring Boot项目中自定义配置Redis密码的加解密方法,通过在`application.yml`文件中配置信息,并在`RedisConfig`类中实现加解密逻辑

Redis密码在springboot自定义加解密

1.application.yml文件配置信息

spring:
  # redis 配置
  redis:
    # 地址
    host: 192.168.1.xxx
    # 端口,默认为6379
    port: 6379
    # 数据库索引
    database: 0
    # 密码,DES加密后,有key值,此处只作为例子
    password: 1E903BC217660491
    # 连接超时时间
    timeout: 10s
    lettuce:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 0
        # 连接池中的最大空闲连接
        max-idle: 8
        # 连接池的最大数据库连接数
        max-active: 8
        # #连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1ms

2.RedisConfig中代码

package com.framework.config;

import com.common.utils.sign.DESUtil;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;

/**
 * redis配置
 * 
 * @author elane
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{
    private final Environment environment;
    public RedisConfig(Environment environment){
        this.environment=environment;
    }

    @Bean
    public RedisConnectionFactory myLettuceConnectionFactory(){
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(environment.getProperty("spring.redis.host"),Integer.parseInt(environment.getProperty("spring.redis.port")));
        redisStandaloneConfiguration.setDatabase(Integer.parseInt(environment.getProperty("spring.redis.database")));
        //获取application.yml 中的密码(密文)
        String password = environment.getProperty("spring.redis.password");
        //解密密码并停驾到配置中
        String pwd=DESUtil.encrypt("111111");//此处用于生成加密后的密码,配置在配置文件中
        redisStandaloneConfiguration.setPassword(DESUtil.decrypt(password));
        return new LettuceConnectionFactory(redisStandaloneConfiguration);
    }

    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
        //connectionFactory获取到的密码就是解密后的密码
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        serializer.setObjectMapper(mapper);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public DefaultRedisScript<Long> limitScript()
    {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(limitScriptText());
        redisScript.setResultType(Long.class);
        return redisScript;
    }

    /**
     * 限流脚本
     */
    private String limitScriptText()
    {
        return "local key = KEYS[1]\n" +
                "local count = tonumber(ARGV[1])\n" +
                "local time = tonumber(ARGV[2])\n" +
                "local current = redis.call('get', key);\n" +
                "if current and tonumber(current) > count then\n" +
                "    return tonumber(current);\n" +
                "end\n" +
                "current = redis.call('incr', key)\n" +
                "if tonumber(current) == 1 then\n" +
                "    redis.call('expire', key, time)\n" +
                "end\n" +
                "return tonumber(current);";
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 如何利用Redis锁解决高并发问题详解

    如何利用Redis锁解决高并发问题详解

    redis锁处理高并发问题十分常见,下面这篇文章主要给大家介绍了关于如何使用Redis锁解决高并发问题的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧
    2018-09-09
  • Redis常见分布锁的原理和实现

    Redis常见分布锁的原理和实现

    这篇文章主要介绍了Redis常见分布锁的原理和实现,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-08-08
  • 详解Redis中的List是如何实现的

    详解Redis中的List是如何实现的

    List 的 Redis 中的 5 种主要数据结构之一,它是一种序列集合,可以存储一个有序的字符串列表,顺序是插入的顺序,本文将给大家介绍了一下Redis中的List是如何实现的,需要的朋友可以参考下
    2024-05-05
  • redis执行lua脚本的实现

    redis执行lua脚本的实现

    本文主要介绍了redis执行lua脚本的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-10-10
  • Redis高并发防止秒杀超卖实战源码解决方案

    Redis高并发防止秒杀超卖实战源码解决方案

    本文主要介绍了Redis高并发防止秒杀超卖实战源码解决方案,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-10-10
  • 浅谈Redis 中的过期删除策略和内存淘汰机制

    浅谈Redis 中的过期删除策略和内存淘汰机制

    本文主要介绍了Redis 中的过期删除策略和内存淘汰机制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-04-04
  • Redis如何安装部署(单节点)

    Redis如何安装部署(单节点)

    这篇文章主要介绍了Redis如何安装部署(单节点)问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-01-01
  • Redis的共享session应用实现短信登录

    Redis的共享session应用实现短信登录

    本文主要介绍了Redis的共享session应用实现短信登录,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • 浅谈Redis中的内存淘汰策略和过期键删除策略

    浅谈Redis中的内存淘汰策略和过期键删除策略

    本文主要介绍了浅谈Redis中的内存淘汰策略和过期键删除策略,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-09-09
  • Redis接口访问优化的方法步骤

    Redis接口访问优化的方法步骤

    本文基于之前的Redis接口访问进行优化,引入了接口防抖功能,通过时间段参数限制接口调用频率,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-10-10

最新评论