Redis JedisCluster Spring整合

前言:

想用spring直接注入jedisCluster的,但是发现构造函数中的"Set<HostAndPort> nodes"参数无法配置,在网上找到一个例子,这才知道有FactoryBean<T>这个东西,也算是涨姿势了.原版的网址找不到了,但还是很感谢原作者.

1:spring配置JedisCluster

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:redis.properties" />
    </bean>
    <!-- jedis 配置-->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig" >
        <!--最大空闲数-->
        <property name="maxIdle" value="${redis.maxIdle}" />
        <!--最大建立连接等待时间-->
        <property name="maxWaitMillis" value="${redis.maxWait}" />
        <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个-->
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
        <property name="maxTotal" value="${redis.maxTotal}" />
        <property name="minIdle" value="${redis.minIdle}" />
    </bean >
    <bean id="jedisCluster"  class="com.system.util.SimpleJedisCluster" >
        <property name="addressConfig">
            <value>classpath:redis.properties</value>
        </property>
        <property name="addressKeyPrefix" value="cluster" />   <!--  属性文件里  key的前缀 -->
        <property name="timeout" value="300000" />
        <property name="maxRedirections" value="6" />
        <property name="genericObjectPoolConfig" ref="poolConfig" />
    </bean >
</beans>

2:SimpleJedisCluster类

package com.system.util;

import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
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;

/**
 * 类描述:
 *
 * @author fengyong
 * @version 1.0
 * @since 1.0
 * Created by fengyong on 16/10/29 下午4:07.
 */
public class SimpleJedisCluster implements FactoryBean<JedisCluster>, InitializingBean {

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

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

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

    public boolean isSingleton() {
        return true;
    }

    private Set<HostAndPort> parseHostAndPort() {
        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) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public void afterPropertiesSet() throws Exception {
        Set<HostAndPort> haps = this.parseHostAndPort();
        jedisCluster = new JedisCluster(haps, timeout, maxRedirections,poolConfig);
    }
    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 poolConfig) {
        this.poolConfig = poolConfig;
    }
}

3:redis.properties配置
#redis中心
#redis的服务器地址
redis.host=127.0.0.1
#redis的服务端口
redis.port=6379
#密码
redis.password=
#最大空闲数
redis.maxIdle=100
#最大连接数
redis.maxActive=300
#最大建立连接等待时间
redis.maxWait=1000
#客户端超时时间单位是毫秒
redis.timeout=100000
redis.maxTotal=1000
redis.minIdle=8
#明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
redis.testOnBorrow=true

#sentinel
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.node1.host=127.0.0.1
spring.redis.sentinel.node2.host=127.0.0.1
spring.redis.sentinel.node3.host=127.0.0.1
spring.redis.sentinel.node1.port=26379
spring.redis.sentinel.node2.port=26479
spring.redis.sentinel.node3.port=26579
#sentinel

#cluster
cluster1.host.port=127.0.0.1:7000
cluster2.host.port=127.0.0.1:7001
cluster3.host.port=127.0.0.1:7002
cluster4.host.port=127.0.0.1:7003
cluster5.host.port=127.0.0.1:7004
cluster6.host.port=127.0.0.1:7005
cluster7.host.port=127.0.0.1:7006
cluster8.host.port=127.0.0.1:7007
#cluster

4:测试类

package com.test.redis;

import com.test.BaseTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisCluster;

/**
 * 类描述:
 *
 * @author fengyong
 * @version 1.0
 * @since 1.0
 * Created by fengyong on 16/10/29 下午9:00.
 */
public class RedisClusterTest extends BaseTest {
    @Autowired
    private JedisCluster jedisCluster;

    @Test
    public void cluster(){
        jedisCluster.set("foo", "bar");
        String value = jedisCluster.get("foo");
        System.out.println(value);
    }
}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值