• spring集成redis,集成redis集群


    原文:http://chentian114.iteye.com/blog/2292323

    1、通过spring-data-redis集成redis 

    pom.xml依赖包 

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.chen</groupId>
        <artifactId>test_redis02</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
        <build />
        <properties>
            <spring.version>3.1.2.RELEASE</spring.version>
        </properties>
    
        <dependencies>
            <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
            <!-- spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
    
            <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.8.1</version>
    </dependency>
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-redis</artifactId>
                <version>1.7.1.RELEASE</version>
            </dependency>
             <dependency>
         <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
        <version>2.4.2</version>
    </dependency> 
        </dependencies>
    </project>

    spring application-reids.xml配置文件 

    Java代码  收藏代码
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"   
           xmlns:tx="http://www.springframework.org/schema/tx"
        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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            ">
        
        <!-- 加载配置文件 -->
        <context:property-placeholder location="classpath:redis.properties"/>
        <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
            <property name="maxIdle" value="${redis.maxIdle}" />
            <!-- <property name="maxActive" value="${redis.maxActive}" />
            <property name="maxWait" value="${redis.maxWait}" />
            <property name="testOnBorrow" value="${redis.testOnBorrow}" /> -->
        </bean>
        
        <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
            p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"  p:pool-config-ref="poolConfig"/> 
        
        <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
            <property name="connectionFactory"   ref="connectionFactory" />  
        </bean>       
        
    </beans>

    UserDaoImpl.java 

    Java代码  收藏代码
    package com.chen.dao;
    
    import java.io.Serializable;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.dao.DataAccessException;
    import org.springframework.data.redis.connection.RedisConnection;
    import org.springframework.data.redis.core.RedisCallback;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Repository;
    
    import com.chen.pojo.User;
    @Repository
    public class UserDaoImpl implements UserDao {
        
        @Autowired
        private RedisTemplate<Serializable,Serializable> redisTemplate;
    
        public void saveUser(final User user) {
            redisTemplate.execute(new RedisCallback<Object>(){
                @Override
                public Object doInRedis(RedisConnection connection)
                        throws DataAccessException {
                    String str= "user.uid."+user.getId();
                    byte[] key = redisTemplate.getStringSerializer().serialize(str);
                    connection.set(key,redisTemplate.getStringSerializer().serialize(user.getName()));
                    return null;
                }
            });
        }
    
        public User getUser(final long id) {
            return redisTemplate.execute(new RedisCallback<User>(){
                @Override
                public User doInRedis(RedisConnection connection) throws DataAccessException {
                    byte[] key = redisTemplate.getStringSerializer().serialize("user.uid." + id);
                    if(connection.exists(key)) {
                        byte[] value = connection.get(key);
                        String name = redisTemplate.getStringSerializer().deserialize(value);
                        User user = new User();
                        user.setName(name);
                        user.setId(id);
                        return user;
                    }
                    return null;
                }
            });
        }
    
    }

    2、通过jedis集成redis 

    spring applicationContext.xml配置文件 

    Java代码  收藏代码
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"   
           xmlns:tx="http://www.springframework.org/schema/tx"
        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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            ">
        
        <!-- 加载配置文件 -->
        <context:property-placeholder location="classpath:redis.properties"/>
        <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
            <property name="maxIdle" value="${redis.maxIdle}" />
            <!-- <property name="maxActive" value="${redis.maxActive}" />
            <property name="maxWait" value="${redis.maxWait}" />
            <property name="testOnBorrow" value="${redis.testOnBorrow}" /> -->
        </bean>
        <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" scope="singleton">
            <constructor-arg index="0" ref="jedisPoolConfig" />
            <constructor-arg index="1">
                <list>
                    <bean class="redis.clients.jedis.JedisShardInfo">
                        <constructor-arg name="host" value="${redis.host}" />
                        <constructor-arg name="port" value="${redis.port}" />
                        <!-- <constructor-arg name="timeout" value="${redis.timeout}" /> -->
                    </bean>
                </list>
            </constructor-arg>
        </bean>
          
        
    </beans>

    RedisDataSourceImpl.java 

    Java代码  收藏代码
    package com.chen.redis;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    
    import redis.clients.jedis.ShardedJedis;
    import redis.clients.jedis.ShardedJedisPool;
    @Repository("redisDataSource")
    public class RedisDataSourceImpl implements RedisDataSource {
        
        @Autowired
        private ShardedJedisPool shardedJedisPool;
        
        public ShardedJedis getRedisClient() {
            try{
                ShardedJedis shardJedis = shardedJedisPool.getResource();
                return shardJedis;
            }catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }
    
        public void returnResource(ShardedJedis shardedJedis) {
            shardedJedisPool.returnResource(shardedJedis);
        }
    
        public void returnResource(ShardedJedis shardedJedis, boolean broken) {
            if(broken){
                shardedJedisPool.returnBrokenResource(shardedJedis);
            }else{
                shardedJedisPool.returnResource(shardedJedis);
            }
        }
    
    }

    RedisClientTemplate.java 

    Java代码  收藏代码
    package com.chen.redis;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    
    import redis.clients.jedis.ShardedJedis;
    
    @Repository("redisClientTemplate")
    public class RedisClientTemplate {
        @Autowired
        private RedisDataSource redisDataSource;
        
        public void disconnect(){
            ShardedJedis shardedJedis = redisDataSource.getRedisClient();
            shardedJedis.disconnect();
        }
        
        public String set(String key,String val){
            String result = null ;
            ShardedJedis jedis = redisDataSource.getRedisClient();
            if(jedis ==null)return null;
            boolean broken = false;
            try{
                result = jedis.set(key, val);
            }catch(Exception e){
                e.printStackTrace();
                broken = true ;
            }finally{
                redisDataSource.returnResource(jedis,broken);
            }
            return result;
        }
        
        public String get(String key){
            String result = null;
            ShardedJedis jedis = redisDataSource.getRedisClient();
            if(jedis==null)return result;
            boolean broken = false;
            try{
                result = jedis.get(key);
            }catch(Exception e){
                e.printStackTrace();
                broken= true;
            }finally{
                redisDataSource.returnResource(jedis,broken);
            }
            return result;
        }
    }

    DemoTest.java 

    Java代码  收藏代码
     
    package com.chen.demo;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.chen.redis.RedisClientTemplate;
    
    public class DemoTest {
        private static ApplicationContext apx;
        static{
            apx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        }
        
        @Test
        public void test1(){
            String key1 = "mykey1"; String val1 = "myvalue1";
            RedisClientTemplate template = (RedisClientTemplate) apx.getBean("redisClientTemplate");
            String result = template.set(key1, val1);
            System.out.println("result="+result);
        }
        
        @Test
        public void test2(){
            String key1 = "mykey1";
            RedisClientTemplate template = (RedisClientTemplate) apx.getBean("redisClientTemplate");
            String val1 = template.get(key1);
            System.out.println(val1);
        }
    }

    详情见test_spring_redis03.rar源码 

    3、通过jedis集成JedisCluster 

    spring applicationContext.xml配置文件 

    Java代码  收藏代码
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"   
           xmlns:tx="http://www.springframework.org/schema/tx"
        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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            ">
        
        <!-- 加载配置文件 -->
        <context:property-placeholder location="classpath:redis.properties"/>
        <bean name="genericObjectPoolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig">
            <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
            <property name="maxTotal" value="${redis.maxTotal}" />
            <property name="minIdle" value="${redis.minIdle}" />
            <property name="maxIdle" value="${redis.maxIdle}" />
        </bean>
        
        <bean id="jedisCluster" class="com.chen.redis.JedisClusterFactory">
            <property name="addressConfig">
                <value>classpath:connect-redis.properties</value>
            </property>
            <property name="addressKeyPrefix" value="address"></property>
            <property name="timeout" value="${redis.timeout}" />
            <property name="maxRedirections" value="${redis.maxRedirections}" />
            <property name="genericObjectPoolConfig" ref="genericObjectPoolConfig"></property>
        </bean>
        
    </beans>

    集群服务器配置文件 
    connect-redis.properties 

    Java代码  收藏代码
    address1=192.168.199.130:7001
    address2=192.168.199.130:7002
    address3=192.168.199.130:7003
    address4=192.168.199.130:7004
    address5=192.168.199.130:7005
    address6=192.168.199.130:7006

    JedisClusterFactory.java 

    Java代码  收藏代码
    package com.chen.redis;  
    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 String password;
    
        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, 2000, maxRedirections, password, 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;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
    }

    DemoTest.java 

    Java代码  收藏代码
    package com.chen.demo;
    
    import org.junit.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import redis.clients.jedis.JedisCluster;
    
    public class DemoTest {
        private static ApplicationContext apx;
        static{
            apx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        }
        
        
        @Test
        public void test1(){
            JedisCluster jedisCluster = (JedisCluster) apx.getBean("jedisCluster");
            String key1="myname1";
            String key2="myname2";
            String key3="myname3";
            System.out.println(jedisCluster.get(key1));
            System.out.println(jedisCluster.get(key2));
            System.out.println(jedisCluster.get(key3));
            
        }
        
        @Test
        public void test2(){
            JedisCluster jedisCluster = (JedisCluster) apx.getBean("jedisCluster");
            String key1="mystring1"; String val1 = "myval1";
            String key2="mystring2"; String val2 = "myval2";
            String key3="mystring3"; String val3 = "myval3";
            System.out.println(jedisCluster.set(key1,val1));
            System.out.println(jedisCluster.set(key2,val2));
            System.out.println(jedisCluster.set(key3,val3));
            System.out.println("----------------------");
            System.out.println(jedisCluster.get(key1));
            System.out.println(jedisCluster.get(key2));
            System.out.println(jedisCluster.get(key3));
        }
    }

  • 相关阅读:
    h5之js生成二维码
    h5手势密码开发(使用jq)
    html可用于跨域的三个标签
    原生js实现ajax
    js中parentNode,parentElement,childNodes,children
    js字符串操作之substr与substring
    pyhton之os.path
    [bzoj1510][POI2006]Kra-The Disks_暴力
    [bzoj4994][Usaco2017 Feb]Why Did the Cow Cross the Road III_树状数组
    [bzoj2506]calc_分块处理
  • 原文地址:https://www.cnblogs.com/shihaiming/p/6049794.html
Copyright © 2020-2023  润新知