Spring Boot Redis多实例配置

1,添加redis依赖 pom.xml

<dependency>
<groupId>org.springframework.boot</groupId><!-- 会附带引进jedis的包 -->
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
2,main/resource目录下新建redis.properties

#===============Redis配置=========================
#redis连接池配置
#最大连接数
spring.redis.pool.max-active=8
#最大空闲连接数
spring.redis.pool.max-idle=8
#连接池阻塞等待时间
spring.redis.pool.max-wait=-1
spring.redis.pool.min-idle=0

#redis cluster集群配置
spring.redis.sentinel.master= # Name of Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.

#redis多实例配置,但至少要配一组作为默认配置
#默认redis
spring.redis.database=0
spring.redis.host=10.213.43.4
spring.redis.port=11121
spring.redis.timeout=0

#redis2
spring.redis2.database=0
spring.redis2.host=10.213.45.10
spring.redis2.port=11121
spring.redis2.timeout=0

#redis3
#....
 

 

3,新建配置类RedisConfig

package com.demo.common.config;

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.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.lang.reflect.Method;

/**
* Redis多实例配置
*/
@Configuration
@EnableCaching
public class RedisConfig {

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

@Bean
public KeyGenerator keyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* 创建连接
* @param host
* @param port
* @param timeout
* @return
*/
public JedisConnectionFactory newJedisConnectionFactory(int index,String host,int port,int timeout){
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setDatabase(index);
factory.setHostName(host);
factory.setPort(port);
factory.setTimeout(timeout); //设置连接超时时间

//testOnBorrow为true时,返回的连接是经过测试可用的
factory.setPoolConfig(poolCofig(redisPoolMaxIdle,redisPoolMinIdle,redisPoolMaxActive,redisPoolMaxWait,true));

System.out.println("redis config========="+host);
return factory;
}

@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
// Number of seconds before expiration. Defaults to unlimited (0)
//cacheManager.setDefaultExpiration(10); //设置key-value超时时间
return cacheManager;
}


public JedisPoolConfig poolCofig(int maxIdle, int minIdle,int maxTotal,long maxWaitMillis,boolean testOnBorrow) {
JedisPoolConfig poolCofig = new JedisPoolConfig();
poolCofig.setMaxIdle(maxIdle);
poolCofig.setMinIdle(minIdle);
poolCofig.setMaxTotal(maxTotal);
poolCofig.setMaxWaitMillis(maxWaitMillis);
poolCofig.setTestOnBorrow(testOnBorrow);
return poolCofig;
}

public void setSerializer(RedisTemplate template) {
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);
template.setValueSerializer(jackson2JsonRedisSerializer);
    template.setKeySerializer(new StringRedisSerializer());
    }
}
 

4,配置多实例1-为默认配置

DefaultRedisConfig.java
package com.demo.common.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

//PropertySource注解设置使用的resource目录下配置文件名称,
//不设置默认为resource/application.properties
//@PropertySource(value = "classpath:/redis.properties")
@Configuration
@EnableCaching
public class DefaultRedisConfig extends RedisConfig {

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

    @Primary
    @Bean
    public JedisConnectionFactory defaultRedisConnectionFactory() {
        return newJedisConnectionFactory(dbIndex,host, port, timeout);
    }

    @Bean(name = "DefaultRedisTemplate")
    public RedisTemplate defaultRedisTemplate() {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(defaultRedisConnectionFactory());
        setSerializer(template);
        template.afterPropertiesSet();
        return template;
    }

    @Bean(name = "DefaultStringRedisTemplate")
    public StringRedisTemplate defaultStringRedisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(defaultRedisConnectionFactory());
        template.afterPropertiesSet();
        return template;
    }
}

 

5,配置第二个实例

package com.demo.common.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;


//@PropertySource(value = "classpath:/redis.properties")
@Configuration
@EnableCaching
public class ArticleRedisConfig extends RedisConfig {

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


    @Bean
    public JedisConnectionFactory articleRedisConnectionFactory() {
        return newJedisConnectionFactory(dbIndex,host, port, timeout);
    }


    @Bean(name = "ArticleRedisTemplate")
    public RedisTemplate articleRedisTemplate() {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(articleRedisConnectionFactory());
        setSerializer(template); //设置序列化工具,这样ReportBean不需要实现Serializable接口
        template.afterPropertiesSet();
        return template;
    }


    @Bean(name = "ArticleStringRedisTemplate")
    public StringRedisTemplate articleStringRedisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(articleRedisConnectionFactory());
        template.afterPropertiesSet();
        return template;
    }

}

 

6,使用方法


@Autowired
@Resource(name = "DefaultStringRedisTemplate")
private StringRedisTemplate defaultStringRedis;

@Autowired
@Resource(name = "ArticleStringRedisTemplate")
private StringRedisTemplate articleStringRedis;

@Autowired
@Resource(name = "DefaultRedisTemplate")
private RedisTemplate defaultRedis;

@Autowired
@Resource(name = "ArticleRedisTemplate")
private RedisTemplate articleRedis;


public void test() {

defaultStringRedis.opsForValue().set("zzzz","11111111111");
articleStringRedis.opsForValue().set("zzzz","22222222222");


System.out.println("defaultStringRedis======"+defaultStringRedis.opsForValue().get("zzzz"));
System.out.println("articleStringRedis======"+articleStringRedis.opsForValue().get("zzzz"));

ArticleBase defaultAritle=new ArticleBase();
defaultAritle.setId(12);
defaultRedis.opsForValue().set("test1" , defaultAritle);

ArticleBase testAritle=new ArticleBase();
testAritle.setId(13);
articleRedis.opsForValue().set("test1" , testAritle);


ArticleBase getdefaultAritle=(ArticleBase)defaultRedis.opsForValue().get("test1");
ArticleBase gettestAritle=(ArticleBase)articleRedis.opsForValue().get("test1");

System.out.println("defaultRedis==="+getdefaultAritle.getId());
System.out.println("articleRedis==="+gettestAritle.getId());

}
 

 



    原文作者:redis
    原文地址: https://www.cnblogs.com/lchb/articles/7222870.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞