在我的虚拟机上安装了三台linux red hat6
版本redis3.0.6
192.168.1.81 redis 的master
192.168.1.82 slave
192.168.1.83 slave
注意配置ip和防火墙的关闭
81上redis的配置
port 6379
82,83上redis的配置
port 6379
slaveof 192.168.1.81 6379
从服务器上就多了个主的配置
sentinel的配置基本是默认的
下面使用spring-data-redis来配置集群
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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-4.2.xsd"
default-lazy-init="true">
<description>cache 缓存配置</description>
<bean id="redisSentinelConfiguration"
class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
<property name="master">
<bean class="org.springframework.data.redis.connection.RedisNode">
<property name="name" value="mymaster">
</property>
</bean>
</property>
<property name="sentinels">
<set>
<bean class="org.springframework.data.redis.connection.RedisNode">
<constructor-arg name="host" value="192.168.1.81">
</constructor-arg>
<constructor-arg name="port" value="26379">
</constructor-arg>
</bean>
<bean class="org.springframework.data.redis.connection.RedisNode ">
<constructor-arg name="host" value="192.168.1.82" />
<constructor-arg name="port" value="26379" />
</bean>
<bean class="org.springframework.data.redis.connection.RedisNode ">
<constructor-arg name="host" value="192.168.1.83" />
<constructor-arg name="port" value="26379" />
</bean>
</set>
</property>
</bean>
<bean id="jeidsConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<constructor-arg ref="redisSentinelConfiguration" />
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jeidsConnectionFactory" />
<property name="keySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean
class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashValueSerializer">
<bean
class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
</bean>
</beans>
再看看maven pom.xml的配置
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
在java中使用缓存
@Autowired
private RedisTemplate redisTemplate;
///
ValueOperations<String, Object> valueOper=redisTemplate.opsForValue();
valueOper.set(key,value);
测试下主从切换
我把master关闭之后,自动切换到83上面
3209:X 19 Jan 12:55:17.432 # +sdown slave 192.168.1.81:6379 192.168.1.81 6379 @ mymaster 192.168.1.83 6379
运行redis-cli
keys *
可以看到ok了