Springmvc集成redis集群
2017-01-11 12:04
645 查看
先说以下需要加入的jar,maven
属性文件的配置
Spring-redis.xml文件的配置
一个工厂类
一个序列化工具类
最后一个测试类
<!--使用Redis客户端:Jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!--protosuff 序列化依赖 --> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-core</artifactId> <version>1.0.8</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.7.2.RELEASE</version> </dependency>
属性文件的配置
address1=192.168.63.129:7001 address2=192.168.63.129:7002 address3=192.168.63.129:7003 address4=192.168.63.129:7004 address5=192.168.63.129:7005 address6=192.168.63.129:7006 #客户端超时时间单位是毫秒 redis.timeout=300000 #最大连接数 redis.maxActive=1024 #最小空闲数 redis.minIdle=8 #最大空闲数 redis.maxIdle=100 #最大建立连接等待时间 redis.maxWaitMillis=1000 #redis集群单位数 redis.maxRedirections=6 #这里和你的redis数据库个数一样 redis.testOnBorrow=true
Spring-redis.xml文件的配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 读取配置文件信息 --> <context:property-placeholder ignore-unresolvable="true" location="classpath:properties/redis-cluster.properties"/> <!-- jedis cluster config --> <bean id="genericObjectPoolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig"> <property name="maxTotal" value="1024" /> <property name="minIdle" value="8" /> <property name="maxIdle" value="100" /> <property name="maxWaitMillis" value="1000" /> <property name="testOnBorrow" value="true" /> </bean> <bean id="jedisCluster" class="com.cn.dlnu.common.utils.JedisClusterFactory"> <property name="addressConfig" value="classpath:properties/redis-cluster.properties"/> <property name="addressKeyPrefix" value="address" /> <property name="timeout" value="300000" /> <!--代表集群有几台redis--> <property name="maxRedirections" value="6" /> <property name="genericObjectPoolConfig" ref="genericObjectPoolConfig" /> </bean> </beans>
一个工厂类
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: 工厂类 * @Modified By:Ming Created in 23:07 2017/1/10 */ 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 var9) { throw var9; } catch (Exception var10) { throw new Exception("解析 jedis 配置文件失败", var10); } } 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; } }
一个序列化工具类
package com.cn.dlnu.common.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * @version V1.0 * @Description: * @Modified By:Ming Created in 23:14 2017/1/10 */ public class SerializerUtil { /** * 序列化 * @param object * @return */ public static byte[] serializeObj(Object object) { ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(object); byte[] bytes = baos.toByteArray(); return bytes; } catch (Exception e) { throw new RuntimeException("序列化失败!", e); } } /** * 反序列化 * @param bytes * @return */ public static Object deserializeObj(byte[] bytes) { if (bytes == null){ return null; } ByteArrayInputStream bais = null; try { bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { throw new RuntimeException("反序列化失败!", e); } } }
最后一个测试类
package com.cn.dlnu.dao.cache; import com.cn.dlnu.MetendMethod; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * RedisCache Tester. * * @author <Authors name> * @version 1.0 * @since <pre>01/10/2017</pre> */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring/spring-applicationContext.xml", "classpath:/spring/spring-redis.xml"}) public class RedisCacheTest { @Resource private RedisCache redisCache; /** * Method: putCache(String key, T obj) */ @Test public void testPutCache() throws Exception { List<String> list = new ArrayList<>(); list.add("测试list"); list.add("测试list2"); redisCache.putCache("testList","redis集群测试"); redisCache.putCache("name","123123"); Map<String,Object> map = new HashMap<String, Object>(); map.put("test*","测试数据"); map.put("测试数据","啥的"); map.put("listTest",list); redisCache.putCache("testMap",map); redisCache.putCache("testString","redis集群测试"); Map resultMap = new HashMap(); resultMap.put("testList",redisCache.getCache("testList")); resultMap.put("testMap",redisCache.getCache("testMap")); resultMap.put("testString",redisCache.getCache("testString")); System.out.print(map); } /** * Method: putCacheWithExpireTime(String key, T obj, final int expireTime) */ @Test public void testPutCacheWithExpireTime() throws Exception { } /** * Method: getCache(final String key) */ @Test public void testGetCache() throws Exception { System.out.println(redisCache.getCache("name").toString()); } }
demo下载地址http://download.csdn.net/detail/u013412790/9734603
相关文章推荐
- Pedis: NoSQL data store using the SEASTAR framework, compatible with Redis
- redis安装问题小结
- RedHat 5.8 安装Oracle 11gR2_Grid集群
- spring中Redis的集群简单实现
- Shiro学习之路 Hello Shiro(一)
- mysql集群之MMM简单搭建
- 使用 Redis 和 Python 构建一个共享单车的应用程序
- Redis偶发连接失败案例实战记录
- Redis中实现查找某个值的范围
- win 7 安装redis服务【笔记】
- redis的hGetAll函数的性能问题(记Redis那坑人的HGETALL)
- Redis和Memcached的区别详解
- Redis02 使用Redis数据库(String类型)全面解析
- 分割超大Redis数据库例子
- Redis总结笔记(一):安装和常用命令
- Redis有序集合类型的常用命令小结
- Redis sort 排序命令详解
- 用Redis实现微博关注关系