redis 集群在代码中运用

2018-07-05  本文已影响0人  丿灬小朋

**本篇介绍springmvc+redis 集群的使用

注意: jedis-2.9.0 以上版本才支持密码配置连接,并且spring需要spring4.x以上版本

1、首先加入maven包配置
 <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
</dependency>

2、编写一个spring-redis.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" 
    xmlns:task="http://www.springframework.org/schema/task"
    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
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
    
    <!-- redis 配置 -->
    <bean name="genericObjectPoolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig" >
             <!--最大建立连接等待时间,默认为-1-->  
            <property name="maxWaitMillis" value="-1" />
            <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接 
                        并尝试取出另一个-->  
            <property name="testOnBorrow" value="true" />
            <property name="maxTotal" value="1000" />
            <property name="minIdle" value="8" />
            <!--最大空闲数-->  
            <property name="maxIdle" value="100" />
    </bean>

        <!-- 这个是自己的一个redis工厂类--> 
    <bean id="jedisCluster" class="com.testhu.myredis.JedisClusterFactory">
        <property name="addressConfig">
            <value>classpath:myredis.properties</value>
        </property>

               <!--  属性文件里  key的前缀 -->
        <property name="addressKeyPrefix" value="redisaddress" />  
              <!--    连接超时 -->
        <property name="timeout" value="400000" />
        <property name="maxRedirections" value="8" />
        <property name="genericObjectPoolConfig" ref="genericObjectPoolConfig" />
    </bean>
    
    
</beans>

3、编写myredis.properties配置文件 (这里根据你自己的ip地址填写,以及端口,此处只做举列)

redisaddress1=127.0.0.1:7001
redisaddress2=127.0.0.1:7002
redisaddress3=127.0.0.1:7003
redisaddress4=127.0.0.1:7004
redisaddress5=127.0.0.1:7005
redisaddress6=127.0.0.1:7006
4、把spring-redis.xml 要加入到web.xml 扫描中
5、JedisClusterFactory工厂类代码
package com.testhu.myredis;

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;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;
/**
 * @version V1.0
 * @Description: 工厂类
 * @auth :hu
 */
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*$");

    public JedisClusterFactory() {
    }

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

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

    public boolean isSingleton() {
        return true;
    }

    private Set<HostAndPort> parseHostAndPort() throws Exception {
        try {
            Properties ex = new Properties();
            ex.load(this.addressConfig.getInputStream());
            HashSet haps = new HashSet();
            Iterator i$ = ex.keySet().iterator();

            while(i$.hasNext()) {
                Object key = i$.next();
                if(((String)key).startsWith(this.addressKeyPrefix)) {
                    String val = (String)ex.get(key);
                    boolean isIpPort = this.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 ex2) {
            throw ex2;
        } catch (Exception ex1) {
            throw new Exception("解析 jedis 配置文件失败", ex1);
        }
    }

    public void afterPropertiesSet() throws Exception {
        Set haps = this.parseHostAndPort();
        this.jedisCluster = new JedisCluster(haps, this.timeout.intValue(), this.maxRedirections.intValue(), 
        this.genericObjectPoolConfig);
    }

    public void setAddressConfig(Resource addressConfig) {
        this.addressConfig = addressConfig;
    }

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

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

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

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


6、使用的时候,使用注入即可

@Autowired
private JedisCluster jedisCluster;  

做我们能做的!改变我们能改变的!

上一篇 下一篇

猜你喜欢

热点阅读