`

redis-cluster与spring-data-redis集成

阅读更多
因为redis3.0才出来,spring-data-redis正式版本还没有支持redis-cluster。大概上官网看了一下,发现只有1.7.0.RC1才支持,同时没有找到关于jedis与spring-data-redis集成RedisTemplate的资料,所以看了一下原码,写了下面关于RedisTemplate的配置。
引用

一、redis-cluster构造
引用


二、与spring-data-redis集成
1.JedisCluster
以集群方式使用连接池,来直接使用redis相关命令。
spring.xml
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="${redis.maxTotal}" />
		<property name="maxIdle" value="${redis.maxIdle}" />
		<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
		<property name="testOnBorrow" value="${redis.testOnBorrow}" />
		<property name="testOnReturn" value="${redis.testOnReturn}" />
	</bean>

    <bean id="redisConnectionFactory"
        class="com.sinowel.eacpa.test.JedisClusterFactory">
        <property name="addressConfig">
            <value>classpath:connect-redis.properties</value>
        </property>
        <!-- 属性文件里 key的前缀 -->
        <property name="addressKeyPrefix" value="address" />

        <property name="timeout" value="300000" />
        <property name="maxRedirections" value="6" />
        <property name="genericObjectPoolConfig" ref="jedisPoolConfig" />
    </bean>

connect-redis.properties
address1=192.168.71.188:6380
address2=192.168.71.188:6381
address3=192.168.71.188:6382
address4=192.168.71.188:7380
address5=192.168.71.188:7381
address6=192.168.71.188:7382

import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

public class JedisClusterFactory implements FactoryBean<JedisCluster>, InitializingBean {

    private Resource addressConfig;
    private String addressKeyPrefix ;

    private JedisCluster jedisCluster;
    private Integer timeout;
    private Integer maxRedirections;
    private GenericObjectPoolConfig genericObjectPoolConfig;
    
    private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$");

    @Override
    public JedisCluster getObject() throws Exception {
        return jedisCluster;
    }

    @Override
    public Class<? extends JedisCluster> getObjectType() {
        return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);
    }

    @Override
    public boolean isSingleton() {
        return true;
    }



    private Set<HostAndPort> parseHostAndPort() throws Exception {
        try {
            Properties prop = new Properties();
            prop.load(this.addressConfig.getInputStream());

            Set<HostAndPort> haps = new HashSet<HostAndPort>();
            for (Object key : prop.keySet()) {

                if (!((String) key).startsWith(addressKeyPrefix)) {
                    continue;
                }

                String val = (String) prop.get(key);

                boolean isIpPort = p.matcher(val).matches();

                if (!isIpPort) {
                    throw new IllegalArgumentException("ip 或 port 不合法");
                }
                String[] ipAndPort = val.split(":");

                HostAndPort hap = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1]));
                haps.add(hap);
            }

            return haps;
        } catch (IllegalArgumentException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new Exception("解析 jedis 配置文件失败", ex);
        }
    }
    
    @Override
    public void afterPropertiesSet() throws Exception {
        Set<HostAndPort> haps = this.parseHostAndPort();
        
        jedisCluster = new JedisCluster(haps, timeout, maxRedirections,genericObjectPoolConfig);
//        jedisCluster = new JedisCluster(haps, timeout, genericObjectPoolConfig);
    }
    public void setAddressConfig(Resource addressConfig) {
        this.addressConfig = addressConfig;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public void setMaxRedirections(int maxRedirections) {
        this.maxRedirections = maxRedirections;
    }

    public void setAddressKeyPrefix(String addressKeyPrefix) {
        this.addressKeyPrefix = addressKeyPrefix;
    }

    public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) {
        this.genericObjectPoolConfig = genericObjectPoolConfig;
    }

}

引用


2.RedisTemplate
以集群方式使用连接池,来使用模板进行数据操作,key与value自动序列化存储。
spring.xml
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="${redis.maxTotal}" />
		<property name="maxIdle" value="${redis.maxIdle}" />
		<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
		<property name="testOnBorrow" value="${redis.testOnBorrow}" />
		<property name="testOnReturn" value="${redis.testOnReturn}" />
	</bean>

    <!-- <bean id="redisNode" class="org.springframework.data.redis.connection.RedisNode">
        <property name=""></property>
    </bean> -->
    <bean id="redisClusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
        <property name="maxRedirects" value="3" />
        <property name="clusterNodes">
            <set>
                <!-- <ref bean="redisNode" /> -->
                
	            <bean class="org.springframework.data.redis.connection.RedisNode">
	                <constructor-arg name="host" value="192.168.71.188"></constructor-arg> 
	                <constructor-arg name="port" value="7380"></constructor-arg>
	            </bean>
                <!-- <bean class="org.springframework.data.redis.connection.RedisNode">
                    <constructor-arg name="host" value="192.168.71.188"></constructor-arg> 
                    <constructor-arg name="port" value="6381"></constructor-arg>
                </bean>
                <bean class="org.springframework.data.redis.connection.RedisNode">
                    <constructor-arg name="host" value="192.168.71.188"></constructor-arg> 
                    <constructor-arg name="port" value="6382"></constructor-arg>
                </bean> -->
            </set>
        </property>
    </bean>
    
    <bean id="redis4CacheConnectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <constructor-arg name="clusterConfig" ref="redisClusterConfig" />
        
		<property name="hostName" value="${redis.host}"/>
		<property name="port" value="${redis.port}"/>
		<property name="timeout" value="${redis.timeout}" />
		<property name="poolConfig" ref="jedisPoolConfig"/>
	</bean>

	<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />
	<bean id="redis4CacheTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="redis4CacheConnectionFactory" />
        <!-- <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property> -->
        <property name="keySerializer" ref="stringRedisSerializer" />
        <property name="hashKeySerializer" ref="stringRedisSerializer" />
        <property name="valueSerializer" ref="stringRedisSerializer" />
        <property name="hashValueSerializer" ref="stringRedisSerializer" />
	</bean>


引用
spring-data-redis提供了多种serializer策略,这对使用jedis的开发者而言,实在是非常便捷。sdr提供了4种内置的serializer:
JdkSerializationRedisSerializer:使用JDK的序列化手段(serializable接口,ObjectInputStrean,ObjectOutputStream),数据以字节流存储
StringRedisSerializer:字符串编码,数据以string存储
JacksonJsonRedisSerializer:json格式存储
OxmSerializer:xml格式存储
其中JdkSerializationRedisSerializer和StringRedisSerializer是最基础的序列化策略,其中“JacksonJsonRedisSerializer”与“OxmSerializer”都是基于stirng存储,因此它们是较为“高级”的序列化(最终还是使用string解析以及构建java对象)。
RedisTemplate中需要声明4种serializer,默认为“JdkSerializationRedisSerializer”:
    1) keySerializer :对于普通K-V操作时,key采取的序列化策略
    2) valueSerializer:value采取的序列化策略
    3) hashKeySerializer: 在hash数据结构中,hash-key的序列化策略
    4) hashValueSerializer:hash-value的序列化策略
    无论如何,建议key/hashKey采用StringRedisSerializer。
http://www.360doc.com/content/15/0513/21/1073512_470277654.shtml

3. 测试代码
@Service
public class TestService {

    @Resource
    private JedisCluster redisConnectionFactory;
//
    @Resource
    private RedisTemplate redis4CacheTemplate;
    
    public void test() {
        System.out.println(redisConnectionFactory.get("t1"));
        System.out.println(redisConnectionFactory.get("aa"));
        System.out.println(redisConnectionFactory.get("cc"));
        System.out.println("----------------");
        redis4CacheTemplate.opsForValue().set("aa", "300人");
        redis4CacheTemplate.opsForValue().set("cc", "AA1");
        redis4CacheTemplate.opsForValue().set("t4", "BB");
        System.out.println(redis4CacheTemplate.opsForValue().get("aa"));
        System.out.println(redis4CacheTemplate.opsForValue().get("cc"));
        System.out.println(redis4CacheTemplate.opsForValue().get("t44"));

    }
}

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import com.sinowel.eacpa.BaseTest;
import com.sinowel.eacpa.test.service.TestService;

@RunWith(BlockJUnit4ClassRunner.class)
public class TestDemo extends BaseTest{

    public TestDemo() {
        super("classpath:spring/spring.xml");
    }
        
    @Test //测试构造注入
    public void testCons() {
        TestService service = super.getBean("testService");
        service.test();
        System.out.println("success");
    }
}

控制台输出:
100
300人
AA1
----------------
300人
AA1
null
分享到:
评论
1 楼 songsir01 2018-04-08  
Invalid property 'maxRedirects' of bean class [org.springframework.data.redis.connection.RedisClusterConfiguration]: Bean property 'maxRedirects' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
这是什么原因呢

相关推荐

    redis-cluster和spring集成,基于cache注解

    综上所述,"redis-cluster和spring集成,基于cache注解" 的项目是一个使用 Spring Cache 集成 Redis 集群的实例,旨在通过注解的方式简化缓存管理,提高应用性能。开发者可以通过导入提供的项目,快速了解和实践这一...

    spring redis-cluster 整合

    当业务需求涉及分布式环境时,Redis集群(redis-cluster)就显得尤为重要。本文将深入探讨如何在Spring MVC项目中整合Spring与Redis集群。 首先,让我们理解什么是Redis集群。Redis集群是一种分布式解决方案,通过...

    redis-6.2.12可执行安装包

    Redis,全称Remote Dictionary Server,是一款高性能的键值存储系统,常被用于...而`redis-6.2.12-cluster`则可能是用于搭建和管理Redis集群的关键文件,对于运维人员来说,理解和掌握Redis的使用和集群管理至关重要。

    spring-data-redis-1.0.2

    Spring Data Redis通过提供与这些数据结构对应的Java对象,使得与它们的交互变得直观且高效。 此外,Spring Data Redis还集成了Spring Framework的事务管理功能,允许开发者在Redis操作中实现事务控制。尽管Redis...

    spring-boot-demo-cluster-redis-websocket.zip

    本项目"spring-boot-demo-cluster-redis-websocket.zip"就是这样一个示例,它演示了如何在Spring Boot应用中利用WebSocket进行实时通信,并通过Redis实现消息的集群共享。 首先,让我们了解一下Spring Boot。Spring...

    redis-cluster结合springboot的使用自定义序列化

    当Redis与SpringBoot结合使用时,可以轻松地将缓存功能集成到Java应用中。本教程将深入探讨如何在SpringBoot应用中设置和使用Redis集群,并自定义序列化方法以便更方便地查看和管理缓存数据。 首先,我们来了解`...

    RedisCluster集群(Spring访问Redis)

    **RedisCluster集群与Spring访问Redis详解** Redis是一个高性能的键值数据库,广泛应用于缓存、消息中间件等场景。在大型分布式系统中,为了提供高可用性和数据冗余,我们通常会采用Redis Cluster来构建集群。本文...

    spring-data-redis-1.6.0.RELEASE.jar + jedis-2.7.2.jar包

    综上所述,"spring-data-redis-1.6.0.RELEASE.jar + jedis-2.7.2.jar"组合提供了Spring应用程序与Redis交互的强大工具集,涵盖了从基本操作到复杂应用场景的各种功能。在实际开发中,你需要根据项目需求选择合适的...

    springcloud部署redis集群

    SpringCloud通过集成Spring Data Redis模块,使得在微服务架构中与Redis进行交互变得非常便捷。以下将详细介绍如何在SpringCloud中配置和使用Redis集群。 首先,你需要了解Redis集群的基本概念。Redis集群通过数据...

    SpringBoot集成Redis-Demo

    SpringBoot集成Redis-Demo是一个关于如何在Java应用中利用SpringBoot框架与Redis进行集成的实践教程。在这个项目中,我们将探讨如何配置、使用以及优化SpringBoot应用中的Redis数据存储。 首先,SpringBoot简化了...

    SpringMVC整合Redis集群

    项目由maven构建,使用springMVC整合了Redis的集群,发布到tomcat中,访问http://localhost:8080/SpringRedisCluster/redis/hello.do测试即可,前提是配好了redis的集群。

    redis集群以及Spring-data-redis操作集群

    Spring-data-redis是Spring框架提供的用于操作Redis的库,它支持与Redis集群的交互。在Spring应用中,可以使用`JedisCluster`类来操作Redis集群。 1. **依赖引入**:在项目中添加Spring-data-redis和Jedis的相关...

    redis-2.6.jar

    在实际应用中,"redis-2.6.jar"可能还会与其他组件结合使用,比如Spring框架中的`spring-data-redis`,它提供了更高级别的抽象和自动化管理,简化了Redis的集成。同时,你还需要了解Redis的持久化、主从复制、...

    springboot-redis-demo

    下面我们将详细探讨SpringBoot如何与Redis进行整合,并分析项目"springboot-redis-demo"中可能包含的关键知识点。 1. **添加依赖**: 在SpringBoot项目中,我们首先需要在`pom.xml`或`build.gradle`文件中添加...

    spring-data-redis 1.7.6

    《深入解析Spring-data-redis 1.7.6与源码分析》 Spring-data-redis是Spring框架下针对Redis数据库的扩展,它提供了一种在Java应用中方便、高效地使用Redis的方法。版本1.7.6是该库的一个稳定版本,包含了一系列的...

    redis cluster spring整合代码

    Spring Data Redis是Spring Framework的一个子项目,旨在简化与Redis数据库的交互。它提供了一种声明式的方法来处理Redis操作,如键值对的存取、哈希、集合、有序集合等。通过Repository接口,开发者可以很方便地...

    spring-data-redis

    Spring Data Redis能很好地与其他Spring框架集成,如Spring Cache可以利用Redis作为缓存后端,Spring Session可以使用Redis存储用户的会话信息,Spring Cloud Data Flow可以利用Redis作为任务调度的存储。...

    Java-redis-demo

    11. **Spring Data Redis**: 如果你的项目使用了Spring框架,Spring Data Redis模块可以简化与Redis的集成,提供了一套基于注解的编程模型。 12. **性能调优**: 使用Redis时,需要关注数据结构的选择、过期策略、...

    解压即用Redis-x64-3.2.100.zip

    在Spring框架中集成Redis,可以使用`spring-data-redis`库,该库提供了RedisTemplate和ReactiveRedisTemplate,便于操作Redis数据。同时,Spring Boot提供了自动配置,简化了集成过程。在大数据处理中,Redis常作为...

    springboot整合redis集群零配置

    在Spring Boot中,我们可以通过引入`spring-boot-starter-data-redis`依赖来启用Redis支持。但是,要配置Redis集群,通常需要设置多个节点地址、密码、端口等信息。在Spring Boot 2.1及以上版本中,我们可以利用`...

Global site tag (gtag.js) - Google Analytics