springboot+redisTemplate多库操作

news2024/9/25 9:39:04
单库操作
  • 我做了依赖管理,所以就不写版本号了
  • 添加依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
  • 配置文件
spring:
  redis:
    database: 2
    host: 127.0.0.1
    port: 6379
    password: 123456
  • redisTemplate配置
    /**
    * @author liouwb
    */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DateUtil.DateStyle.YYYY_MM_DD_HH_MM_SS.getValue());
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
        om.registerModule(javaTimeModule);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.setDefaultSerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
  • 使用
    @Autowired(required = false)
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void testRedis() {
        redisTemplate.opsForValue().set("redisTemplate", "redisTemplate");
        Object value = redisTemplate.opsForValue().get("redisTemplate");
        System.out.println("redis设置的值为:" + value);
    }

在这里插入图片描述

  • 能够正常往redis设置数据,也可以正常获取到
    在这里插入图片描述
  • 可以看到数据库编号是yml里面配置的database编号
多库操作
  • 使用lettuce连接池,添加commons-pools依赖
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
  • 配置类
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * redis数据库配置
 *
 * @author liouwb
 */
@Data
@Configuration
public class RedisConfigProperties {
    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    /**
     * 连接超时时间
     * 目前不从配置文件获取
     */
    private int timeout = 200;

    private int maxActive = 200;

    private int maxIdle = 8;

    private int minIdle = 0;

    private int maxWait = 100;
}
  • 配置连接池
    /**
     * redis连接池
     *
     * @author liouwb
     * @rutern org.apache.commons.pool2.impl.GenericObjectPoolConfig
     */
    @Bean
    public GenericObjectPoolConfig getPoolConfig() {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(redisConfigProperties.getMaxActive());
        poolConfig.setMaxIdle(redisConfigProperties.getMaxIdle());
        poolConfig.setMinIdle(redisConfigProperties.getMinIdle());
        poolConfig.setMaxWaitMillis(redisConfigProperties.getMaxWait());
        return poolConfig;
    }
  • 设置redisTemplate操作模版工厂类
    /**
     * RedisTemplate连接工厂
     *
     * @param database数据库编号
     * @author liouwb
     * @rutern org.springframework.data.redis.core.RedisTemplate<java.lang.String, java.lang.Object>
     */
    private RedisTemplate<String, Object> redisTemplateFactory(int database) {
        // 构建工厂对象
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(redisConfigProperties.getHost());
        configuration.setPort(redisConfigProperties.getPort());
        configuration.setPassword(RedisPassword.of(redisConfigProperties.getPassword()));
        LettucePoolingClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder()
                .commandTimeout(Duration.ofSeconds(redisConfigProperties.getTimeout())).poolConfig(getPoolConfig()).build();
        // 连接工厂
        LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration, clientConfiguration);
        // 设置使用的redis数据库
        factory.setDatabase(database);
        // 重新初始化工厂
        factory.afterPropertiesSet();

        // 序列化配置
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DateUtil.DateStyle.YYYY_MM_DD_HH_MM_SS.getValue());
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
        om.registerModule(javaTimeModule);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 初始化连接
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 设置连接工厂
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.setDefaultSerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
  • 设置对应数据库的redisTemplate模版类
    /**
     * db0 第一个库
     *
     * @author liouwb
     * @time 2024-01-03
     * @rutern org.springframework.data.redis.core.RedisTemplate<java.lang.String, java.lang.Object>
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate0() {
        return this.redisTemplateFactory(0);
    }

    /**
     * db1 第二个库
     *
     * @author liouwb
     * @rutern org.springframework.data.redis.core.RedisTemplate<java.lang.String, java.lang.Object>
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate1() {
        return this.redisTemplateFactory(1);
    }
  • 对不同redis库进行操作
    @Autowired(required = false)
    @Qualifier("redisTemplate0")
    private RedisTemplate<String, Object> redisTemplate0;
    @Autowired(required = false)
    @Qualifier("redisTemplate1")
    private RedisTemplate<String, Object> redisTemplate1;

     @Test
    public void testRedis() {
        redisTemplate0.opsForValue().set("redisTemplate0", "redisTemplate0");
        Object value0 = redisTemplate0.opsForValue().get("redisTemplate0");
        System.out.println("redis0设置的值为:" + value);

        redisTemplate1.opsForValue().set("redisTemplate1", "redisTemplate1");
        Object value1 = redisTemplate0.opsForValue().get("redisTemplate1");
        System.out.println("redis1设置的值为:" + value1);
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1364568.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

钡铼技术BL110智能网关功能介绍 | PLC程序的上传和下载

在工业自动化系统中&#xff0c;PLC&#xff08;可编程逻辑控制器&#xff09;是一种常见的控制设备。通常情况下&#xff0c;PLC被用于监控、控制和调节生产过程中的各种设备和机器。而PLC一旦出现故障&#xff0c;就会影响到下控设备的工作状态&#xff0c;进而影响整个工厂的…

K8S本地开发环境-minikube安装部署及实践

引言 在上一篇介绍了k8s的入门和实战&#xff0c;本章就来介绍一下在windows环境如何使用minikube搭建K8s集群&#xff0c;好了废话不多说&#xff0c;下面就和我一起了解Minikube吧。 什么是Minikube&#xff1f; Minikube 是一种轻量级的 Kubernetes 实现&#xff0c;可在本…

0.9uA 低功耗低压差稳压器

一、基本概述 FM6215 系列采用 CMOS 工艺制造的高精度、低功耗低压差稳压器。该系列具有极低的静态电流, 输出电压 3.3v的产品静态功耗仅为 0.9uA(TYP),最大输出电流可达到 300mA。 产品采用 SOT23-5 封装&#xff0c;因此&#xff0c;该系列适用于需要高密度安装的应用场合&a…

【AI视野·今日Sound 声学论文速览 第四十期】Wed, 3 Jan 2024

AI视野今日CS.Sound 声学论文速览 Wed, 3 Jan 2024 Totally 4 papers &#x1f449;上期速览✈更多精彩请移步主页 Daily Sound Papers Auffusion: Leveraging the Power of Diffusion and Large Language Models for Text-to-Audio Generation Authors Jinlong Xue, Yayue De…

记一个React组件入参不当导致页面卡死的问题

一、问题描述 1.1 触发现象 点击按钮后页面卡死 1.2 最小 Demo CodeSandBox&#xff1a;https://codesandbox.io/p/sandbox/react-hook-component-stuck-755wcyinscode&#xff1a;https://inscode.csdn.net/ import ./App.css; import React, { useState, useEffect } f…

2023年全国职业院校技能大赛(高职组)“云计算应用”赛项赛卷4

某企业根据自身业务需求&#xff0c;实施数字化转型&#xff0c;规划和建设数字化平台&#xff0c;平台聚焦“DevOps开发运维一体化”和“数据驱动产品开发”&#xff0c;拟采用开源OpenStack搭建企业内部私有云平台&#xff0c;开源Kubernetes搭建云原生服务平台&#xff0c;选…

Redis反序列化的一次问题

redis反序列化的一次问题 1. 问题描述 springbootredis不少用&#xff0c;但是一直没遇到什么问题&#xff0c;直接代码拷贝上去就用了。这次结合spring-security&#xff0c;将自定义的spring-security的UserDetails接口的实现类SecurityUser&#xff0c;反序列化取出时报错…

Packet Tracer - Configure Cisco Routers for Syslog, NTP, and SSH Operations

Packet Tracer - 配置Cisco路由器以实现Syslog、NTP和SSH功能 地址表 目标&#xff1a; 配置OSPF MD5身份验证。配置NTP服务。设置路由器将消息记录到syslog服务器。配置R3路由器以支持SSH连接。 背景/场景&#xff1a; 在本练习中&#xff0c;您将配置OSPF MD5身份验证以实…

一文快速搞懂Nginx —— Nginx 详解

一文快速搞懂Nginx 一、niginx 简介二、正向 / 反向代理2.1 正向代理2.2 反向代理 三、负载均衡四、动静分离五、web 缓存六、Niginx 安装6.1 windows版本下的安装6.2 Linux版本下的安装 七、常用命令八、为什么选择Nginx 一、niginx 简介 Nginx 同 Apache 一样都是一种 Web 服…

C语言光速入门笔记

C语言是一门面向过程的编译型语言&#xff0c;它的运行速度极快&#xff0c;仅次于汇编语言。C语言是计算机产业的核心语言&#xff0c;操作系统、硬件驱动、关键组件、数据库等都离不开C语言&#xff1b;不学习C语言&#xff0c;就不能了解计算机底层。 目录 C语言介绍C语言特…

PAT 乙级 1056 组合数的和

给定 N 个非 0 的个位数字&#xff0c;用其中任意 2 个数字都可以组合成 1 个 2 位的数字。要求所有可能组合出来的 2 位数字的和。例如给定 2、5、8&#xff0c;则可以组合出&#xff1a;25、28、52、58、82、85&#xff0c;它们的和为330。 输入格式&#xff1a; 输入在一行…

水母目标检测数据集VOC格式500张

水母&#xff0c;一种美丽而神秘的海洋生物&#xff0c;以其独特的形态和生态习性而备受瞩目。 水母的体型呈伞状&#xff0c;身体透明&#xff0c;有各种颜色和花纹。它们没有骨骼&#xff0c;身体由胶状物质组成&#xff0c;非常柔软和脆弱。水母通过触手上的刺细胞释放毒素…

Unity 一文掌握使用AddListener方法为组件事件添加监听器的方法

在Unity中&#xff0c;很多组件都带有事件&#xff0c;比如: Button组件&#xff1a;onClick() Toggle组件&#xff1a;On Value Changed(Boolean) Dropdown组件&#xff1a;On Value Changed(Int32) InputField组件&#xff1a;On Value Changed(String)、On End Edit(Stri…

【leetcode】力扣算法之有效的数独【中等难度】

题目描述 请你判断一个 9 x 9 的数独是否有效。只需要 根据以下规则 &#xff0c;验证已经填入的数字是否有效即可。 数字 1-9 在每一行只能出现一次。数字 1-9 在每一列只能出现一次。数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。&#xff08;请参考示例图&…

CodeWave智能开发平台--03--目标:应用创建--07供应商数据表格

摘要 本文是网易数帆CodeWave智能开发平台系列的第09篇&#xff0c;主要介绍了基于CodeWave平台文档的新手入门进行学习&#xff0c;实现一个完整的应用&#xff0c;本文主要完成07供应商数据表格 CodeWave智能开发平台的09次接触 CodeWave参考资源 网易数帆CodeWave开发者…

Micro-app 微前端框架demo介绍

Micro-app 框架 1、框架安装 npm i micro-zoe/micro-app --save2、子应用对应的view页面 <template><div><!-- name(必传)&#xff1a;应用名称url(必传)&#xff1a;应用地址&#xff0c;会被自动补全为http://localhost:3000/index.htmlbaseroute(可选)&…

mysql进阶-重构表

目录 1. 原因 2. 如何重构表呢&#xff1f; 2.1 命令1&#xff1a; 2.2 命令2&#xff1a; 2.3 命令3&#xff1a; 1. 原因 正常的业务开发&#xff0c;为什么需要重构表呢&#xff1f; 原因1&#xff1a;某张表存在大量的新增和删除操作&#xff0c;导致表经历过大量的…

Kali Linux——设置中文

【问题现象】 从下图可以看到&#xff0c;菜单全是英文的。对于英文不好的同学&#xff0c;使用起来很难受。 【解决方法】 1、获取root权限 su root 2、进入语言设置 dpkg-reconfigure locales 3、选择zh_CN.UTF-8 UTF-8 4、设置默认 5、安装完成 6、重启虚拟机 reboot…

多租户看这一篇就够了

什么是多租户&#xff1f;举个例子&#xff1a;马云、马化腾和刘强东三个人去租房子&#xff0c;他们因为家里经济困难所以勤工俭学&#xff0c;三个人决定合租一套三室一厅的房子&#xff0c;虽然每个人有自己的房间&#xff0c;但是家里的水电、厨房、卫生间和热水器都是大家…

强化学习的数学原理学习笔记 - 蒙特卡洛方法(Monte Carlo)

文章目录 概览&#xff1a;RL方法分类蒙特卡洛方法&#xff08;Monte Carlo&#xff0c;MC&#xff09;MC BasicMC Exploring Starts&#x1f7e6;MC ε-Greedy 本系列文章介绍强化学习基础知识与经典算法原理&#xff0c;大部分内容来自西湖大学赵世钰老师的强化学习的数学原理…