spring整合redis集群配置密码_redis默认密码

spring整合redis集群配置密码_redis默认密码创作背景springboot2集成redis集群网上的例子已经很多了,但涉及到密码几乎都是明文,这在实际生产环境中,是不允许的,特写此文章。源码片段第一步:pom.xml<?xmlversion=”1.0″encoding=”UTF-8″?><projectxmlns=”http://maven.apache.org/POM/4.0.0″xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

创作背景

springboot2 集成redis集群网上的例子已经很多了,但涉及到密码几乎都是明文,这在实际生产环境中,是不允许的,特写此文章。

源码片段

第一步:pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
    </parent>

    <groupId>com.wu</groupId>
    <artifactId>springbootKafka</artifactId>
    <version>0.0.1</version>
    <name>springbootKafka</name>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
       
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
       
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.6.7</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka-test</artifactId>
            <scope>test</scope>
        </dependency>
       
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.3.RELEASE</version>
            </plugin>
        </plugins>
    </build>
</project>

第二步:配置 application.yml

spring:
  main:
    web-application-type: none #去除web,以纯java的模式启动springboot
  redis:
    cluster:
      nodes: 192.168.1.101:8001,192.168.1.101:8002,192.168.1.102:8001,192.168.1.102:8002,192.168.1.103:8001,192.168.1.103:8002
      max-redirects: 3  # 获取失败 最大重定向次数
    pool:
      max-active: 1000  # 连接池最大连接数(使用负值表示没有限制)
      max-idle: 10    # 连接池中的最大空闲连接
      max-wait: -1   # 连接池最大阻塞等待时间(使用负值表示没有限制)
      min-idle: 5     # 连接池中的最小空闲连接
    timeout: 6000  # 连接超时时长(毫秒)
    password: FC7EF9622A3D2B62 #redis加密密码
logging:
  level:
    root: info

以上重点是这一句:

password: FC7EF9622A3D2B62

redis密码不是明文的,而是通过des加密过的。

DesUtils.java
package com.wu.kafka.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

public final class DesUtils {
    private static final String DES = "DES";
    private static final String KEY = "comwukafka"; //默认密钥

    private DesUtils() {}

    private static byte[] encrypt(byte[] src, byte[] key) throws Exception {
        SecureRandom sr = new SecureRandom();
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(DES);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);
        return cipher.doFinal(src);
    }

    private static byte[] decrypt(byte[] src, byte[] key) throws Exception {
        SecureRandom sr = new SecureRandom();
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(DES);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);
        return cipher.doFinal(src);
    }

    private static String byte2hex(byte[] b) {
        String hs = "";
        String temp = "";
        for (int n = 0; n < b.length; n++) {
            temp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (temp.length() == 1)
                hs = hs + "0" + temp;
            else
                hs = hs + temp;
        }
        return hs.toUpperCase();

    }

    private static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException("length not even");
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }

    public static String decode(String src, String key) {
        String decryptStr = "";
        try {
            byte[] decrypt = decrypt(hex2byte(src.getBytes()), key.getBytes());
            decryptStr = new String(decrypt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptStr;
    }

    public static String encode(String src, String key){
        byte[] bytes = null;
        String encryptStr = "";
        try {
            bytes = encrypt(src.getBytes(), key.getBytes());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (bytes != null)
            encryptStr = byte2hex(bytes);
        return encryptStr;
    }

    /**
     * 解密
     */
    public static String decode(String src) {
        return decode(src, KEY);
    }

    /**
     * 加密
     */
    public static String encode(String src) {
        return encode(src, KEY);
    }
}

第三步:自定义 RedisConnectionFactory,不采用默认逻辑

package com.wu.kafka.config;

import com.wu.kafka.util.DesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class RedisConfig {

    private final Environment environment;
    public RedisConfig(Environment environment) {
        this.environment = environment;
    }

    @Bean(name = "myredisConnectionFactory")
    public RedisConnectionFactory myLettuceConnectionFactory() {
        Map<String, Object> source = new HashMap<String, Object>();
        source.put("spring.redis.cluster.nodes", environment.getProperty("spring.redis.cluster.nodes"));
        source.put("spring.redis.cluster.timeout", environment.getProperty("spring.redis.cluster.timeout"));
        source.put("spring.redis.cluster.max-redirects", environment.getProperty("spring.redis.cluster.max-redirects"));
        MapPropertySource mapPropertySource = new MapPropertySource("RedisClusterConfiguration", source);
        RedisClusterConfiguration  redisClusterConfiguration = new RedisClusterConfiguration(mapPropertySource);

        //获取application.yml 中的密码(密文)
        String password = environment.getProperty("spring.redis.password");
        //解密密码并停驾到配置中
        redisClusterConfiguration.setPassword(DesUtils.decode(password));

        return new LettuceConnectionFactory(redisClusterConfiguration);
    }

    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(@Qualifier("myredisConnectionFactory") RedisConnectionFactory factory) {
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(factory);
        return template;
    }

    @Bean
    public StringRedisTemplate createStringRedisTemplate(@Qualifier("myredisConnectionFactory") RedisConnectionFactory factory){
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory);
        stringRedisTemplate.setKeySerializer(new StringRedisSerializer());
        stringRedisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return stringRedisTemplate;
    }

}

第四步 使用

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void test(){
        stringRedisTemplate.boundValueOps("name").set("wuchao", 500, TimeUnit.SECONDS);
        String name = stringRedisTemplate.boundValueOps("name").get();
        System.out.println(name);
    }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/196807.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • Web安全之业务逻辑漏洞

    Web安全之业务逻辑漏洞业务逻辑不同的项目有不同的功能,不同的功能需要不同的代码实现,实现这些核心功能的代码就叫业务逻辑。业务逻辑漏洞业务逻辑漏洞是指由于程序逻辑不严谨或逻辑太复杂,导致一些逻辑分支不能正常处理或处理错误。常见的业务逻辑漏洞业务逻辑漏洞挖掘过程确定业务流程—>寻找流程中可以被操控的环节—>分析可被操控环节中可能产生的逻辑问题—>尝试修改参数触发逻辑问题业务逻辑漏洞1.URL跳转漏洞1.1.URL跳转概述1.2.触发方式及绕或技巧1.3.修复方法2.短信邮箱轰炸漏洞2.1.短信邮.

  • docker(11)Dockerfile 中的COPY与ADD 命令[通俗易懂]

    docker(11)Dockerfile 中的COPY与ADD 命令[通俗易懂]前言Dockerfile中提供了两个非常相似的命令COPY和ADD,本文尝试解释这两个命令的基本功能,以及其异同点,然后总结其各自适合的应用场景。Build上下文的概念在使用dock

  • hive基础总结(面试常用)

    hive基础总结(面试常用)

    2021年11月27日
  • 常见的嵌入式linux学习和如何选择ARM芯片问答

    常见的ARM嵌入式学习问答,设计者和学习者最关心的11个问题:1.      ARM嵌入式是学习硬件好还是学习软件好?2.      嵌入式软件和硬件,哪一种职位待遇更高?或者说,在设计中哪一个更重要?3.      学完51单片机后,想买ARM开发板继续学习,是买ARM7还是ARM9?4.      到底是学习哪种内核:ARM7、CORTEX-M3、COR

  • 个人网站可以申请微信授权登录吗

    个人网站可以申请微信授权登录吗

    2021年10月25日
  • js中数组的splice方法_vue中splice方法

    js中数组的splice方法_vue中splice方法JavaScript中的splice主要用来对js中的数组进行操作,包括删除,添加,替换等。1.删除-用于删除元素,两个参数,第一个参数(要删除第一项的位置),第二个参数(要删除的项数) 2.插入-向数组指定位置插入任意项元素。三个参数,第一个参数(插入位置),第二个参数(0),第三个参数(插入的项) 3.替换-向数组指定位置插入任意项元素,同时删除任意数量的项,三个参数。第一个参数(

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号