当前位置: 首页 > news >正文

spring boot3-redis分库及配置

Java的Maven类型,理论不想多说,直接用


1、pom.xml

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

2、博主比较喜欢用application.yml,习惯用application.properties也可以

#库号分组
spring:
  data:
    redis:
      singleNode:
        host: localhost
        port: 6379
      databaseConfigs:
        db0:
          index: 0
        db1:
          index: 1

3、 创建RedisDatabaseConfig类,用来做配置

package com.atguigu.boot3_06_reids.config;//package 自己文件的命名空间路劲,也就是主程序相对了路劲

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Data
@Configuration
@ConfigurationProperties(prefix = "spring.data.redis")
public class RedisDatabaseConfig {

    private SingleNodeConfig singleNode;
    private Map<String, DatabaseConfig> databaseConfigs = new HashMap<>();

    @Data
    public static class SingleNodeConfig {
        private String host;
        private int port;
    }

    @Data
    public static class DatabaseConfig {
        private int index;
    }
}

4、创建RedisTemplateConfig类,注入容器@bean

package com.atguigu.boot3_06_reids.Bean;//package 自己文件的命名空间路劲,也就是主程序相对了路劲

import com.atguigu.boot3_06_reids.config.RedisDatabaseConfig;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisTemplateConfig {

    @Autowired
    private RedisDatabaseConfig redisDatabaseConfig;

    @Bean(name = "redisTemplateDb0")
    public RedisTemplate<String, Object> redisTemplateDb0() {
        return createRedisTemplate(redisDatabaseConfig.getDatabaseConfigs().get("db0").getIndex());
    }

    @Bean(name = "redisTemplateDb1")
    public RedisTemplate<String, Object> redisTemplateDb1() {
        return createRedisTemplate(redisDatabaseConfig.getDatabaseConfigs().get("db1").getIndex());
    }

    private RedisTemplate<String, Object> createRedisTemplate(int databaseIndex) {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(
                redisDatabaseConfig.getSingleNode().getHost(),
                redisDatabaseConfig.getSingleNode().getPort()
        );
        config.setDatabase(databaseIndex);

        LettuceConnectionFactory factory = new LettuceConnectionFactory(config);
        factory.afterPropertiesSet();

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 设置 key 的序列化器
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);

        // 配置 ObjectMapper
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 使用替代方法设置类型验证器
        PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder()
                .allowIfSubType(Object.class)
                .build();
        om.activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.NON_FINAL);

        // 在构造函数中传入 ObjectMapper
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(om, Object.class);
        template.setValueSerializer(jackson2JsonRedisSerializer);

        // 设置 Hash 的 key 和 value 的序列化器
        template.setHashKeySerializer(stringRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();
        return template;
    }
}

5、调用

@RestController
public class RedisController {
    @Autowired
    @Qualifier("redisTemplateDb0") //库号0
    private RedisTemplate<String, Object> redisTemplateDb0;

    @Autowired
    @Qualifier("redisTemplateDb1") //库号1
    private RedisTemplate<String, Object>  redisTemplateDb1;

    @GetMapping("/redis")
    public void redis(){
        String uuid = UUID.randomUUID().toString();//生成随机唯一id
        redisTemplateDb0.opsForValue().set("redis", uuid);
        System.out.println("当前:"+redisTemplateDb0.opsForValue().get("redis"));//读值打印
    }

}

http://www.dtcms.com/a/58699.html

相关文章:

  • 微服务与消息队列RabbitMQ
  • Expo知识框架大全详解
  • DQN(Deep Q - Network)原理举例说明
  • 【量化策略】动量延续策略
  • 在Rocky Linux上安装Redis(DNF和源码安装)
  • 网络安全之端口扫描(一)
  • SpringBoot实现文件上传
  • 你为什么要写博客?
  • Linux系统编程--线程同步
  • WangEditor快速实现版
  • 在word下写公式
  • OneM2M:全球性的物联网标准-可应用于物联网中
  • [Kubernetes] 7控制平面组件
  • 排列组合定义及基本公式
  • C++11新特性 10.初始化列表、initializer_list
  • 嵌入式设备的功能安全和信息安全?
  • 数据结构——排序算法第一幕(插入排序:直接插入排序、希尔排序 选择排序:直接选择排序,堆排序)超详细!!!!
  • 物联网中如何增加其可扩展性 协议 网络 设备 还包括软件层面上的
  • 深度相机进行目标物体的空间姿态(位姿)估计
  • 《Linux命令行和shell脚本编程大全》第四章阅读笔记
  • RReadWriteLock读写锁应用场景
  • 第五次CCF-CSP认证(含C++源码)
  • 线性回归机器学习
  • 如何打开文件后缀名
  • 基于大模型的小脑扁桃体下疝畸形全流程预测与诊疗方案研究报告
  • 力扣热题 100:堆专题经典题解析
  • 建筑兔零基础自学记录42|cityengine2019导入sketchup/SU 2
  • 架构思维:高性能架构_01基础概念
  • 2025.3.9总结
  • p5.js:sound(音乐)可视化,动画显示音频高低变化