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);
    }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

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

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • c语言用命令行打开文件_c语言无法打开文件

    c语言用命令行打开文件_c语言无法打开文件linux文件操作(打开及关闭)Linux文件描述符简介当一个进程获取文件的访问权时,通常指打开一个文件时,内核返回一个文件描述符,进程可以通过文件描述符进行后续的操作。文件描述符是一组正整数,每一个文件被打开时,内核都会打开一个大于或等于0的文件描述符。文件描述符012这是linux系统保留的三个文件描述符。0代表标准输入stdin1代表标准输出stdout2代表错误输出s…

    2025年6月17日
    0
  • 详解 & 0xff 的作用

    详解 & 0xff 的作用首先我们要都知道,&表示按位与,只有两个位同时为1,才能得到1,0x代表16进制数,0xff表示的数二进制11111111占一个字节.和其进行&操作的数,最低8位,不会发生变化.下面着重来说说&0xff都有哪些应用:1.只是为了取得低八位通常配合移位操作符>>使用例如:javasocket通信中基于长度的成帧方法中,如果发送的信息长度小于65…

    2022年6月19日
    43
  • c++算法之最长递增子序列(LIS)

    c++算法之最长递增子序列(LIS)题目:输入一个整数n,随后输入n个整数,求这个长度为n的序列中严格递增的子序列的最长长度。例:输入:6143265输出:3解题思路:动态规划。将输入的序列存入一个数组v中,另外再定义一个数组a,用以存储以当前数字v[i]结尾时,最长递增子序列的长度是多少。定义数组时,全部初始化为1,初始状态表示的是最坏的情况,以v[i]结尾的最长递增子序列就是v[i]它本身,长度为1。接着将v[i]逐一…

    2022年6月3日
    26
  • idea 激活码(注册激活)

    (idea 激活码)2021最新分享一个能用的的激活码出来,希望能帮到需要激活的朋友。目前这个是能用的,但是用的人多了之后也会失效,会不定时更新的,大家持续关注此网站~https://javaforall.net/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~4D…

    2022年3月30日
    57
  • 在线校验哈希算法_哈希值查询

    在线校验哈希算法_哈希值查询地址http://www.atool9.com/hash.php

    2022年9月12日
    0
  • jsonObject_jsonobject.tobean

    jsonObject_jsonobject.tobeanJSONObject简介转自:http://blog.csdn.net/huangwuyi/article/details/5412500JSONObject与JSONArray的使用一、JAR包简介     要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包:     1.commons-lang.jar     2.comm

    2022年9月15日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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