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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • pycharm怎么创建虚拟环境_pycharm选择运行环境

    pycharm怎么创建虚拟环境_pycharm选择运行环境配置虚拟环境的必要性1、保持项目的独立性。为每一个项目建立一个独立的运行环境,不与其他项目之间产生环境冲突。(比如其他项目加载或删除依赖环境软件时,互不影响)通俗一点就是,每人一个单间,大家在自己的房间内可以各干各的。2、提升项目开机加载速度。在独立性的前提下,虚拟环境可以选择继承已有的公共环境中的依赖包,也可以完全新建一个空间,也可以将自己的依赖环境共享给其他项目。总之,保证每个项目的虚…

    2022年8月28日
    0
  • vscode好用的插件「建议收藏」

    1.Chinese(Simplified)LanguagePackforVisualStudioCode(汉化vscode必备)2.BracketPairColorizer(给代码中的括号添加亮色便于区分这里截图有报错是特意便于演示写的多组括号)3.AutoCloseTag(自动补全标签必备)4.AutoRenameTag(修改标签名自动同步修改闭合标签的标签名必备)5.ClassautocompleteforHTML(自动补全cl

    2022年4月17日
    233
  • java过滤器的应用(java拦截器的作用)

    Java过滤器是处于客户端与服务器资源文件之间的一道过滤网,在访问资源文件之前,通过一系列的过滤器可以对请求进行修改、判断等,把不符合规则的请求在中途拦截或修改;也可以对响应进行过滤,拦截或修改响应。Java中过滤器也是常用的部分,用于限制某些东西,下面来让我们了解一下吧。过滤器是处于客户端与服务器资源文件之间的一道过滤网,在访问资源文件之前,通过一系列的过滤器对请求进行修改、判断等,把不符合规则…

    2022年4月15日
    141
  • 什么是UE4(学ue4还是unity)

    对于游戏的来说,最能够影响它的性能的,便是游戏程序的开发、维护工作了。游戏开发、维护工作都是通过游戏开发引擎来完成的,而U3D和UE4正是如今行业主流的两款游戏开发引擎。不同的游戏开发引擎在不同的游戏中使用,那么具体的u3d和ue4的区别是什么?小编常被想要进入游戏行业的同学问到,学U3D和UE4哪个更好?其实这主要是看你自己的就业倾向。下面小编就从两款游戏开发引擎的具体区别来讲讲我们该如何选择。…

    2022年4月14日
    57
  • (数据库)数据库分类

    (数据库)数据库分类1.面向操作的关系型数据库典型性应用领域:ERP,CRM,信用卡交易,中小型电商数据储存方法:表格流行厂商:OracleDatabase,MicrosoftSQLServer,IBMDB2,EnterpriseDB(PostgreSQL),MySQL优点:完善的生态环境保护,事务保证/数据一致性缺点:严苛的数据模型界定,数据库拓展限制,和非结构型的结合应用较难。2.面向数据分析的关系型数据库典型性应用领域:数据仓库,商务智能,数据科学研究数据储存方法:表格流行厂商:OracleE

    2022年6月24日
    23
  • es6数组和对象常用方法

    es6数组和对象常用方法数组forEach()方法对数组的每个元素执行一次给定的函数。vararr=[1,2,3]arr.forEach((value,index)=>{console.log(‘数组值:’+value);console.log(‘数组索引:’+index);})map()方法创建一个新数组,其结果是该数组中的每个元素都调用一次提供的函数后的返回值。vararr=[1,2,3]vararr1=arr.map((value,in

    2022年5月26日
    46

发表回复

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

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