美文网首页springbootspringboot
SpringBoot+Redis+Jedis多数据源配置

SpringBoot+Redis+Jedis多数据源配置

作者: superychen | 来源:发表于2019-09-20 12:16 被阅读0次

SpringBoot+Redis+Jedis多数据源配置

环境与工具

开发工具:Intellij Idea
包管理工具:maven
JDK版本:1.8.0_201
SpringBoot版本:2.1.8.RELEASE
SpringDataRedis版本:2.1.10.RELEASE
Jedis-Clients版本:2.9.3

第一步:项目基本框架搭建

参考我的另一篇博客SpringBoot+TkMybatis+Druid单数据源与多数据源配置,包括项目创建,基本配置,基本依赖添加

第二步:先配置下pom,添加redis相关依赖

<?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 https://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.1.8.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.superychen</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--redis相关-开始-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.3</version>
        </dependency>
        <!--redis相关-结束-->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

第三步:集成配置

1.修改application.properties,添加数据源

host,port,password,database根据个人环境自行配置

#redis
spring.redis2.host=127.0.0.1
spring.redis2.port=6379
spring.redis2.password=123qwe
spring.redis.database=0
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.min-idle=1
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1
#redis2
spring.redis2.host=127.0.0.1
spring.redis2.port=6379
spring.redis2.password=123qwe
spring.redis2.database=1

2.编写java配置代码

基本配置类

package com.superychen.demo.config.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import redis.clients.jedis.JedisPoolConfig;

@Component
public class RedisConfig {

    @Value("${spring.redis.jedis.pool.max-active}")
    private int redisPoolMaxActive;
    @Value("${spring.redis.jedis.pool.max-wait}")
    private int redisPoolMaxWait;
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int redisPoolMaxIdle;
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int redisPoolMinIdle;

    /**
     * 创建redis连接工厂
     */
    public JedisConnectionFactory createJedisConnectionFactory(int dbIndex, String host, int port, String password) {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(host);
        redisStandaloneConfiguration.setPort(port);
        redisStandaloneConfiguration.setDatabase(dbIndex);
        redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();
        jpcb.poolConfig(getPoolConfig(redisPoolMaxIdle, redisPoolMinIdle, redisPoolMaxActive, redisPoolMaxWait));
        JedisClientConfiguration jedisClientConfiguration = jpcb.build();
        return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
    }

    /**
     * 设置连接池属性
     */
    public JedisPoolConfig getPoolConfig(int maxIdle, int minIdle, int maxActive, int maxWait) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setMaxWaitMillis(maxWait);
        return poolConfig;
    }

    /**
     * 设置RedisTemplate的序列化方式
     */
    public void setSerializer(RedisTemplate<String, Object> redisTemplate) {
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        //设置键(key)的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置值(value)的序列化方式
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
    }

}

数据源1配置类

package com.superychen.demo.config.redis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
public class DefaultRedisConfig extends RedisConfig {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.database}")
    private int database;

    public RedisConnectionFactory defaultRedisConnectionFactory() {
        return createJedisConnectionFactory(database, host, port, password);
    }

    @Bean(name = "defaultRedisTemplate")
    public RedisTemplate<String, Object> defaultRedisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(defaultRedisConnectionFactory());
        setSerializer(redisTemplate);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}

数据源2配置类

package com.superychen.demo.config.redis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
public class SecondRedisConfig extends RedisConfig {

    @Value("${spring.redis2.host}")
    private String host;
    @Value("${spring.redis2.port}")
    private int port;
    @Value("${spring.redis2.password}")
    private String password;
    @Value("${spring.redis2.database}")
    private int database;

    public RedisConnectionFactory secondRedisConnectionFactory() {
        return createJedisConnectionFactory(database, host, port, password);
    }

    @Bean(name = "secondRedisTemplate")
    public RedisTemplate<String, Object> secondRedisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(secondRedisConnectionFactory());
        setSerializer(redisTemplate);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}

第四步:测试

src/test/java/com/superychen/demo下创建如下测试类

package com.superychen.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MqttMonitorApplicationTests {

    @Resource(name = "defaultRedisTemplate")
    private RedisTemplate<String, Object> defaultRedisTemplate;
    @Resource(name = "secondRedisTemplate")
    private RedisTemplate<String, Object> secondRedisTemplate;

    @Test
    public void contextLoads() {
        defaultRedisTemplate.opsForValue().set("a", "b");
        System.out.println(defaultRedisTemplate.opsForValue().get("a"));
        secondRedisTemplate.opsForValue().set("a", "c");
        System.out.println(secondRedisTemplate.opsForValue().get("a"));

    }

}

执行测试,测试通过

测试结果

查看Redis中数据

数据源1
数据源2

相关文章

网友评论

    本文标题:SpringBoot+Redis+Jedis多数据源配置

    本文链接:https://www.haomeiwen.com/subject/vixjuctx.html