前段时间说过单例redis数据库的方法,但是生成环境一般不会使用,基本上都是集群redis数据库,所以这里说说集群redis的代码。

1、pom.xml引入jar

<!--Redis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>

2、在redis.properties文件里面配置redis的地址和端口(ps:这个属性文件只配置redis集群的地址和端口,方便以后扩展)

address1=redis服务器IP:6379
address2=redis服务器IP:6379
address3=redis服务器IP:6379
address4=redis服务器IP:6379
address5=redis服务器IP:6379
address6=redis服务器IP:6379

3、新建一个属性文件redisconfig.properties配置其他的redis集群环境

#客户端超时时间单位是毫秒
redis.timeout=300000
#最大连接数
redis.maxActive=300
#最小空闲数
redis.minIdle=8
#最大空闲数
redis.maxIdle=100
#最大建立连接等待时间
redis.maxWaitMillis=1000
#redis集群单位数
redis.maxRedirections=6 //这里和你的redis数据库个数一样

4、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"/> <!-- jedis cluster config -->
<bean name="genericObjectPoolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig" >
<property name="maxTotal" value="${redis.maxActive}" />
<property name="minIdle" value="${redis.minIdle}" />
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
</bean> <bean id="jedisCluster" class="com.topteam.redis.JedisClusterFactory">
<property name="addressConfig" value="classpath:redis.properties"/>
<property name="addressKeyPrefix" value="address" /> <property name="timeout" value="${redis.timeout}" />
<property name="maxRedirections" value="${redis.maxRedirections}" />
<property name="genericObjectPoolConfig" ref="genericObjectPoolConfig" />
</bean>
</beans>

5、序列化和反序列化工具代码

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; /**
* 序列化和反序列化工具
*/
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);
}
}
}

6、自己新建一个JedisClusterFactory.java集群工厂类

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; /**
* 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*$"); 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;
}
}

7、操作实现类,这里只提供了3个实现方法,其他的可以根据需求来

(ps:我这里是通过序列化方式来实现的key和value,所以不需要分List集合还是String字符串,统一对待,统一处理)

import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster; import javax.annotation.Resource; /**
* Created by chengwenwen on 2016/11/4.
*/
@Component
public class RedisCache { @Resource
private JedisCluster jedisCluster; /**
* 添加缓存数据
* @param key
* @param obj
* @param <T>
* @return
* @throws Exception
*/
public <T> long putCache(String key, T obj) throws Exception {
final byte[] bkey = key.getBytes();
final byte[] bvalue = SerializerUtil.serializeObj(obj);
return jedisCluster.setnx(bkey,bvalue);
} /**
* 添加缓存数据,设定缓存失效时间
* @param key
* @param obj
* @param expireTime
* @param <T>
* @throws Exception
*/
public <T> String putCacheWithExpireTime(String key, T obj, final int expireTime) throws Exception {
final byte[] bkey = key.getBytes();
final byte[] bvalue = SerializerUtil.serializeObj(obj);
String result = jedisCluster.setex(bkey, expireTime,bvalue);
return result;
} /**
* 根据key取缓存数据
* @param key
* @param <T>
* @return
* @throws Exception
*/
public <T> T getCache(final String key) throws Exception {
byte[] result = jedisCluster.get(key.getBytes());
return (T) SerializerUtil.deserializeObj(result);
}
}

8、测试代码

import com.topteam.redis.RedisCache;
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; /**
* 测试类
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test.xml")
public class test {
@Resource
private RedisCache redisCache; @Test
public void test() throws Exception{
List<String> list = new ArrayList<String>();
list.add("测试list");
list.add("测试list2");
redisCache.putCache("testList","redis集群测试"); 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);
}
}

测试结果:

OK,一切正常。这里可以关闭一个主redis数据库服务,然后经过测试,还是可以获取数据。

  

  

Spring + Jedis集成Redis(集群redis数据库)的更多相关文章

  1. Redis集群--Redis集群之哨兵模式

    echo编辑整理,欢迎转载,转载请声明文章来源.欢迎添加echo微信(微信号:t2421499075)交流学习. 百战不败,依不自称常胜,百败不颓,依能奋力前行.--这才是真正的堪称强大!!! 搭建R ...

  2. springboot+shiro+redis(集群redis版)整合教程

    相关教程: 1. springboot+shiro整合教程 2. springboot+shiro+redis(单机redis版)整合教程 3.springboot+shiro+redis(单机red ...

  3. 认识Redis集群——Redis Cluster

    前言 Redis集群分三种模式:主从模式.sentinel模式.Redis Cluster.之前没有好好的全面理解Redis集群,特别是Redis Cluster,以为这就是redis集群的英文表达啊 ...

  4. phpredis Redis集群 Redis Cluster

    官方url: https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#readme 2017年10月29日20:44:25 ...

  5. 【docker】【redis】2.docker上设置redis集群---Redis Cluster部署【集群服务】【解决在docker中redis启动后,状态为Restarting,日志报错:Configured to not listen anywhere, exiting.问题】【Waiting for the cluster to join...问题】

    参考地址:https://www.cnblogs.com/zhoujinyi/p/6477133.html https://www.cnblogs.com/cxbhakim/p/9151720.htm ...

  6. Redis集群的使用测试(Jedis客户端的使用)

    Redis集群的使用测试(Jedis客户端的使用)1.Jedis客户端建议升级到最新版(当前为2.7.3),这样对3.0.x集群有比较好的支持.https://github.com/xetorthio ...

  7. SpringBoot2.0 整合 Redis集群 ,实现消息队列场景

    本文源码:GitHub·点这里 || GitEE·点这里 一.Redis集群简介 1.RedisCluster概念 Redis的分布式解决方案,在3.0版本后推出的方案,有效地解决了Redis分布式的 ...

  8. Redis集群环境搭建实践

    0 Redis集群简介 Redis集群(Redis Cluster)是Redis提供的分布式数据库方案,通过分片(sharding)来进行数据共享,并提供复制和故障转移功能.相比于主从复制.哨兵模式, ...

  9. (七)整合 Redis集群 ,实现消息队列场景

    整合 Redis集群 ,实现消息队列场景 1.Redis集群简介 1.1 RedisCluster概念 2.SpringBoot整合Redis集群 2.1 核心依赖 2.2 核心配置 2.3 参数渲染 ...

  10. 工具推荐-使用RedisInsight工具对Redis集群CURD操作及数据可视化和性能监控

    关注「WeiyiGeek」公众号 设为「特别关注」每天带你玩转网络安全运维.应用开发.物联网IOT学习! 希望各位看友[关注.点赞.评论.收藏.投币],助力每一个梦想. 本章目录 目录 0x00 快速 ...

随机推荐

  1. awk命令速查

    awk与sed.grep一样都是为了加工数据流而做成的文本加工过滤器命令.awk会事先把输入的数据根据字段单位进行分割.在没有制定分割单位的情况下,以输入数据中的空格或Tab为分隔符.与sed相比,它 ...

  2. R for循环之break,next

    next跳出本次循环 break跳出本层循环(当有多个for 循环时,即跳出最近的一个for循环)

  3. excellent cushioning and also vitality go back with this boot

    The particular manufactured fine mesh higher almost addresses the complete boot. Here is the sort of ...

  4. jquery 杂记

    返回指定属性名的属性值:getAttribute() 设置元素的属性值:attr('src',voiceurl) form表单: 序列化表单值: $('#formid').serialize()   ...

  5. spring统一日志管理,切面(@Aspect),注解式日志管理

    step1 开启切面编程 <!-- 开启切面编程(通过配置织入@Aspectj切面 ) --> <aop:aspectj-autoproxy/> <aop:aspectj ...

  6. 2.1、Hibernate多表操作--一对多、多对一、多对多。

    一.什么是一对一.一对多.多对一及多对多关系(以简单的学生和老师的关系为例来说): 1.一对一:学生具有学号和姓名(假定没有同名的学生)这两个属性,那么我知道了学生的学号也就能找到对应的学生姓名,如果 ...

  7. WCF技术内幕 第二章 - 简单的Message

    1.契约 - 接口 (客户端和服务端都要认识Message) namespace WCFService { [ServiceContract(Namespace = "http://wint ...

  8. Matlab与Windows桌面提醒

    最近在实验室用Matlab做实验,一次训练下来最少得也得5到10分钟吧.在Matlab运行的过程中,又不太好去做别的事情,因为5到10分钟的时间实在有点短.但是,眼睁睁看着代码的运行的话,5分钟又实在 ...

  9. Subsonic使用中

    使用中,遇到各种奇葩问题,依依汇总. 1.引用了Subsonic层后,一运行就开始报错,提示未能找到文件!!    //引用后,目标框架可能会被改变,subsonic的默认框架是2.0,请检查框架是否 ...

  10. 我的页面定制CSS代码(SimpleGamboge皮肤)

    我的页面定制CSS代码,针对博客园SimpleGamboge皮肤. 调整: 1.左上图片更换为自己的头像 2.扩大左侧栏宽度,缩小右侧主栏宽度宽度 3.扩大内容页面的评论区宽度,工具图标靠左 4.去广 ...