Springboot統合複数redisデータソース


応用シーン:業務量の向上に伴い、単一のredisデータソースはすでに私たちの需要を満たすことができず、業務はデータキャッシュの問題を解決するために複数のredisデータソースを導入する必要がある.
1まず導入する.propertiesファイルのredisデータソース情報および最大接続数、最小接続数情報

# Redis
spring.redis.master.database=0  
spring.redis.master.host=127.0.0.1
spring.redis.master.port=6379
spring.redis.master.password=
spring.redis.master.timeout=10000
spring.redis.master.max_active=1024
spring.redis.master.max_idle=200
spring.redis.master.max_wait=10000



# Redis\u4ECE\u5E93
spring.redis.slave.host=127.0.0.2
spring.redis.slave.port=6379
spring.redis.slave.password=
spring.redis.slave.timeout=10000
spring.redis.slave.max_active=1024
spring.redis.slave.max_idle=200
spring.redis.slave.max_wait=10000

2 redis ;

1)


@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
	@Value("${spring.redis.master.host}")
	private String host;
	@Value("${spring.redis.master.port}")
	private int port;
	@Value("${spring.redis.master.timeout}")
	private int timeout;
	@Value("${spring.redis.master.password}")
	private String passowrd;


	@Primary
	@Bean
	public RedisConnectionFactory redisRedisConnectionFactory() {
		return createJedisConnectionFactory(host, port, passowrd, timeout);

	}


	/**
	 *   redis    
	 *
	 * @param host
	 * @param port
	 * @param password
	 * @param timeout
	 * @return
	 */
	public JedisConnectionFactory createJedisConnectionFactory(String host, int port, String password, int timeout) {
		JedisConnectionFactory factory = new JedisConnectionFactory();
		factory.setHostName(host);
		factory.setPort(port);
		factory.setPassword(password);
		factory.setTimeout(timeout); //         
		return factory;

	}



	@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();
			}
		};
	}

	@SuppressWarnings("rawtypes")
	@Bean
	public CacheManager cacheManager(RedisTemplate redisTemplate) {
		RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
		//         
		// rcm.setDefaultExpiration(60);// 
		return rcm;
	}

	@Bean(name = "defaultRedisTemplate")
	public RedisTemplate redisTemplate() {
		StringRedisTemplate template = new StringRedisTemplate();
		template.setConnectionFactory(redisRedisConnectionFactory());
		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.afterPropertiesSet();
		return template;
	}

}

2 slave



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.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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 java.lang.reflect.Method;
@Configuration
public class RedisSlaveConfig {
    @Value("${spring.redis.slave.host}")
    private String host;
    @Value("${spring.redis.slave.port}")
    private int port;
    @Value("${spring.redis.slave.timeout}")
    private int timeout;
    @Value("${spring.redis.slave.password}")
    private String passowrd;

    @Bean
    public RedisConnectionFactory redisSlaveConnectionFactory() {
        return createJedisConnectionFactory(host, port, passowrd, timeout);
    }

    /**
     *   redis    
     *
     * @param host
     * @param port
     * @param password
     * @param timeout
     * @return
     */
    public JedisConnectionFactory createJedisConnectionFactory(String host, int port, String password, int timeout) {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(host);
        factory.setPort(port);
        factory.setPassword(password);
        factory.setTimeout(timeout); //         
        return factory;

    }



    @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();
            }
        };
    }

 

    @Bean(name = "salveRedisTemplate")
    public RedisTemplate redisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisSlaveConnectionFactory());
        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.afterPropertiesSet();
        return template;
    }
}

redisservice


@Service
public class RedisSalveServiceImpl   {

    public static long defaultexpireTime = 8640000L;/
 
    @Resource(name ="salveRedisTemplate")
    private RedisTemplate salveRedisTemplate;

    @Override
    public boolean set(final String key, final String value) {
        boolean result = salveRedisTemplate.execute(new RedisCallback() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = salveRedisTemplate.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                return true;
            }
        });
        return result;
    }

    @Override
    public boolean setEx(final String key, final String value, long expiredSeconds) {
        boolean result = salveRedisTemplate.execute(new RedisCallback() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = salveRedisTemplate.getStringSerializer();
                connection.setEx(serializer.serialize(key), expiredSeconds, serializer.serialize(value));
                return true;
            }
        });
        return result;
    }

    /**
      *
     * @param key
     * @param value
     * @return
     */
    @Override
    public boolean setNX(final String key, final String value) {
        boolean result = salveRedisTemplate.execute(new RedisCallback() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = salveRedisTemplate.getStringSerializer();
                connection.setEx(serializer.serialize(key), defaultexpireTime, serializer.serialize(value));
                return true;
            }
        });
        return result;
    }


    @Override
    public String get(final String key) {
        String result = salveRedisTemplate.execute(new RedisCallback() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = salveRedisTemplate.getStringSerializer();
                byte[] value = connection.get(serializer.serialize(key));
                return serializer.deserialize(value);
            }
        });
        return result;
    }


    @Override
    public boolean del(final String key) {
        boolean result = salveRedisTemplate.execute(new RedisCallback() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = salveRedisTemplate.getStringSerializer();
                connection.del(serializer.serialize(key));
                return true;
            }
        });

        return result;
    }

    @Override
    public boolean exist(final String key) {

        boolean result = salveRedisTemplate.execute(new RedisCallback() {
            @Override
            public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
                RedisSerializer serializer = salveRedisTemplate.getStringSerializer();

                return redisConnection.exists(serializer.serialize(key));
            }
        });
        return result;

    }

    @Override
    public boolean setNKey(final String key, final String value) {
        boolean result = salveRedisTemplate.execute(new RedisCallback() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = salveRedisTemplate.getStringSerializer();
//                log.info("Before RedisServiceImpl.setNKey()  " + key + ":" + value);
                return connection.setNX(serializer.serialize(key), serializer.serialize(value));
            }
        });
        log.info("after RedisServiceImpl.setNKey() :" + result);

        return result;
    }

    @Override
    public boolean setNKey(final String key, final String value, long expiredSeconds) {
        boolean result = salveRedisTemplate.execute(new RedisCallback() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = salveRedisTemplate.getStringSerializer();
//                log.info("Before RedisServiceImpl.setNKey()  " + key + ":" + value);
                boolean success = connection.setNX(serializer.serialize(key), serializer.serialize(value));
                if (success) {
                    connection.expire(serializer.serialize(key), expiredSeconds);
                }
                return success;
            }
        });
        log.info("after RedisServiceImpl.setNKey() :" + result);

        return result;
    }


    @Override
    public String getset(final String key, final String value) {
        String result = salveRedisTemplate.execute(new RedisCallback() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = salveRedisTemplate.getStringSerializer();
                log.info("RedisServiceImpl.getset():" + key);
                byte[] value1 = connection.getSet(serializer.serialize(key), serializer.serialize(value));
                return serializer.deserialize(value1);
            }
        });
        return result;

    }

    

}

reidsSalveService 。