首页 > 代码库 > Spring之redis主从复制(非哨兵模式)
Spring之redis主从复制(非哨兵模式)
看了好几天redis了,公司从刚开始的redisluster变成了redis主从,原因是rediscluster不可控,其实是我水平没到,万一出点啥事,我这个负责人都解决不了,那就完了!大数据平台下,如果缓存崩了,所有操作提前全都干到数据库,很能造成数据库的崩溃,所以改用简单的主从复制模式,这样即可控,又直观,下面我将自己这几天整理的代码整理如下:
注意:使用该代码前提是:成功安装redis并已经启动redis主从服务,否则拒绝连接,那是很。。。的
工程目录:
本人习惯:按目录顺序一次往下帖代码
1、创建加载连接池工具
package com.test.connection;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class ClientConnect {
//主库
private JedisPool masterJedisPool;
//从库
private JedisPool slaveJedisPool;
//设置主库
public void setMasterJedisPool(JedisPool masterJedisPool) {
this.masterJedisPool = masterJedisPool;
}
//设置从库
public void setSlaveJedisPool(JedisPool slaveJedisPool) {
this.slaveJedisPool = slaveJedisPool;
}
//获取主库
public Jedis getMasterJedisPool() {
return masterJedisPool.getResource();
}
//获取从库
public Jedis getSlaveJedisPool() {
return slaveJedisPool.getResource();
}
//关闭主库
public void masterClose(JedisPool masterJedisPool){
masterJedisPool.close();
}
//关闭从库
public void slaveClose(JedisPool slaveJedisPool){
slaveJedisPool.close();
}
}
2、为了好看和隐私性强,创建加载路径
package com.test.constant;
public class SysConstants {
public static final String PATH = "classpath:/context/applicationContext.xml";
public static final String BEAN="clientConnect";
}
3、创建实体类
package com.test.entities;
public class User {
protected String companyId;
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTell() {
return tell;
}
public void setTell(String tell) {
this.tell = tell;
}
protected String id;
protected String name;
protected String age;
protected String address;
protected String tell;
}
4、创建操作主数据库的工具方法:
package com.test.Impl;
import java.util.List;
import com.test.entities.User;
import redis.clients.jedis.Jedis;
/**
*
* @author root
*操作主库,实现增、删、改功能
*/
public class MasterRedisImpl {
Jedis jedis;
public MasterRedisImpl(Jedis jedis){
this.jedis=jedis;
}
/**
* 添加
* @param list
*/
public void INSERT(List<User> list) {
for(int i=0;i<list.size();i++){
User user=list.get(i);
//主键
String key = "user:userId:"+user.getId();
//值1
String field1 = "name:";
String value1 = user.getName();
jedis.hset(key, field1, value1);
//值2
String field2 = "age:";
String value2 = user.getAge();
jedis.hset(key, field2, value2);
//值3
String field3 = "address:";
String value3 = user.getAddress();
jedis.hset(key, field3, value3);
//值4
String field4 = "tell:";
String value4 = user.getTell();
jedis.hset(key, field4, value4);
/**
* 添加键值list
* key1=user:userId:
* value1=1,2,3,4,5,6
*
* key2=user:name:
* value2=zhao,hai,dong
*
* key3=user:age
* value3=11,12 ,12,13
*/
//id->list
String listKey="user:userId:";
String listValue="http://www.mamicode.com/user:userId:"+user.getId();
jedis.lpush(listKey, listValue);
//name->list
String listKey1="user:name:";
String listValue1="user:name:"+user.getName()+":"+user.getId();
jedis.rpush(listKey1, listValue1);
// 添加外键
jedis.sadd("user:userId:"+user.getId()+":companyId:", user.getCompanyId());
}
}
/**
* 删除hash表中指定key的n个指定字段
*
* @param key
* @param fields
*/
public void DELETE(String key,String []fields){
String field=null;
for(int i=0;i<fields.length;i++){
field=fields[i];
jedis.hdel(key, field); //删除xjj.h1中的f1和f2
}
}
/**
* 删除hash表中指定key的所有字段
*/
public void DELETEVALUE(String key){
jedis.del(key);
}
/**
* 移除集合中一个或多个成员
*/
public void DELETESET(String key,String []fields){
String field=null;
for(int i=0;i<fields.length;i++){
field=fields[i];
jedis.srem(key, field);
}
}
/**
* LPOP key:移出并获取列表的第一个元素
* @param key
*/
public String DELETELIST(String key){
return jedis.lpop(key);
}
}
5、创建操作从数据库的工具方法:
package com.test.Impl;
import java.util.List;
import java.util.Set;
import redis.clients.jedis.Jedis;
/**
*
* @author root
*读取从库读数据
*/
public class SlaveRedisImpl {
Jedis jedis;
public SlaveRedisImpl(Jedis slaveJedis) {
this.jedis=slaveJedis;
}
/**
* 查询
* 返回哈希表 key中给定域 field的值
*/
public String SELECT(String key,String field){
return jedis.hget(key, field);
}
public String SELECT(String key){
return jedis.get(key);
}
/**
* 查询list,获取指定位置的元素
* @param key
* @return
*/
public List<String> SELECTLIST(String key,int start,int end){
return jedis.lrange(key, start, end);
}
/**
* 在set中获取key对应所有的vlaue
* @param key
* @return
*/
public Set<String> SELECTSET(String key){
return jedis.smembers(key);
}
}
6、创建applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:property-placeholder location="classpath:/property/redis.properties" />
<!-- 连接池配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="http://www.mamicode.com/${redis.maxIdle}" />
<property name="maxTotal" value="http://www.mamicode.com/${redis.maxTotal}" />
<property name="maxWaitMillis" value="http://www.mamicode.com/${redis.maxWaitMillis}" />
<property name="testOnBorrow" value="http://www.mamicode.com/${redis.testOnBorrow}" />
</bean>
<!-- 连接池 -->
<bean id="masterJedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="poolConfig"/>
<constructor-arg index="1" value="http://www.mamicode.com/127.0.0.1" type="java.lang.String"/>
<constructor-arg index="2" value="http://www.mamicode.com/6379" type="int"/>
</bean>
<bean id="slaveJedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="poolConfig"/>
<constructor-arg index="1" value="http://www.mamicode.com/127.0.0.1" type="java.lang.String"/>
<constructor-arg index="2" value="http://www.mamicode.com/6380" type="int"/>
</bean>
<bean id="clientConnect" class="com.test.connection.ClientConnect">
<property name="masterJedisPool" ref="masterJedisPool"/>
<property name="slaveJedisPool" ref="slaveJedisPool"/>
</bean>
</beans>
连接池配置文件redis.properties:
redis.maxIdle=300
redis.maxTotal=600
redis.maxWaitMillis=1000
redis.testOnBorrow=true
下来当然是测试了:
package com.test.main;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.test.Impl.MasterRedisImpl;
import com.test.Impl.SlaveRedisImpl;
import com.test.connection.ClientConnect;
import com.test.constant.SysConstants;
import com.test.entities.User;
import redis.clients.jedis.Jedis;
public class Test {
/**
* 节点信息
* redis.clients.jedis.Jedis@6ceadf59
* redis.clients.jedis.Jedis@e3b7c27
* @param args
*/
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext ctx = new ClassPathXmlApplicationContext(SysConstants.PATH);
ClientConnect redisUtils = (ClientConnect) ctx.getBean(SysConstants.BEAN);
List<User>list=new ArrayList<>();
for(int i=0;i<10;i++){
User user=new User();
user.setId(i+"");
user.setAddress("gansu"+i);
user.setAge(i+"");
user.setName("zhd"+i);
user.setCompanyId("1010111"+i);
user.setTell("15309853180");
list.add(user);
}
//获取主redis库
Jedis mastrJedis=redisUtils.getMasterJedisPool();
//操作主redis库
MasterRedisImpl mastedao=new MasterRedisImpl(mastrJedis);
//添加数据
mastedao.INSERT(list);
//获取从redis库
Jedis slaveJedis=redisUtils.getSlaveJedisPool();
//操作从redis库
SlaveRedisImpl slavedao=new SlaveRedisImpl(slaveJedis);
//查询
String keyHash="user:userId:5";
String filed="name:";
String keyList="user:name:";
int start=0;
int end=2;
String keySet="user:userId:4:companyId:";
String hashValue=http://www.mamicode.com/slavedao.SELECT(keyHash,filed);
System.out.println("hashValue:"+hashValue);
List<String> listValue=http://www.mamicode.com/slavedao.SELECTLIST(keyList, start,end);
System.out.println("listValue:"+listValue.toString());
Set<String> valueSet=slavedao.SELECTSET(keySet);
Iterator<String> it = valueSet.iterator();
while (it.hasNext()) {
String str = it.next();
System.out.println("valueSet:"+str);
}
}
}
以上代码,是我自己整理的,并且完全可以使用的代码,小菜鸟门完全可以复制粘帖;
Spring之redis主从复制(非哨兵模式)