Spring Boot Redis多实例配置

本文详细介绍了如何在Spring Boot项目中整合Redis缓存系统。包括添加依赖、配置属性文件、创建配置类及注入模板等步骤,并提供了具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

spring.redis.database=0
spring.redis.host=192.168.1.1
spring.redis.password= # Login password of the redis server.
spring.redis.pool.max-active=8
spring.redis.pool.max-idle=8
spring.redis.pool.max-wait=-1
spring.redis.pool.min-idle=0
spring.redis.port=11121
spring.redis.sentinel.master= # Name of Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.
spring.redis.timeout=0

spring.redis2.database=1
spring.redis2.host=192.168.1.2
spring.redis2.password= # Login password of the redis server.
spring.redis2.pool.max-active=8
spring.redis2.pool.max-idle=8
spring.redis2.pool.max-wait=-1
spring.redis2.pool.min-idle=0
spring.redis2.port=11126
spring.redis2.sentinel.master= # Name of Redis server.
spring.redis2.sentinel.nodes= # Comma-separated list of host:port pairs.
spring.redis2.timeout=0

复制代码

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.context.annotation.PropertySource;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.lang.reflect.Method;

/**
 * Created by lchb on 2017-7-22.
 */
@Configuration
@PropertySource(value = "classpath:/redis.properties")
@EnableCaching
public class RedisConfig {

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


    @Value("${spring.redis2.host}")
    private String host2;
    @Value("${spring.redis2.port}")
    private int port2;
    @Value("${spring.redis2.timeout}")
    private int timeout2;


    @Bean
    public KeyGenerator wiselyKeyGenerator(){
        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();
            }
        };
    }

    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(host);
        factory.setPort(port);
        factory.setTimeout(timeout); //设置连接超时时间

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

    @Bean
    public JedisConnectionFactory redisArticleConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(host2);
        factory.setPort(port2);
        factory.setTimeout(timeout2); //设置连接超时时间
        System.out.println("redis config========="+host2);
        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;
    }

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

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


    public RedisConnectionFactory connectionFactory(String hostName, int port ) {
        JedisConnectionFactory jedis = new JedisConnectionFactory();
        jedis.setHostName(hostName);
        jedis.setPort(port);

        //jedis.setPoolConfig(poolCofig(maxIdle, maxTotal, maxWaitMillis,testOnBorrow));
        // 初始化连接pool
        jedis.afterPropertiesSet();
        RedisConnectionFactory factory = jedis;
        return factory;
    }

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

    private void setSerializer(StringRedisTemplate 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);
    }

}

复制代码

4,使用方法

复制代码

@Autowired
    @Resource(name = "redisArticleTemplate")
    private StringRedisTemplate temple;

    @Autowired
    @Resource(name = "redisDefaultTemplate")
    private StringRedisTemplate temple2;


    public void test() {
        temple.opsForValue().set("xxxx","wwwwwwwwwwwwwwwwwwwwwwww");
        System.out.println("xxxxxxxxx======"+temple.opsForValue().get("xxxx"));


        temple2.opsForValue().set("zzzz","mmmmmmmmmmmmmmmmmmmmmmmmmmmmm");
        System.out.println("zzzzzzzzz======"+temple2.opsForValue().get("zzzz"));
    }

复制代码

 

转载于:https://my.oschina.net/appnet/blog/1480247

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值