Redis服务器的部署方式可分为单机和集群的方式,使用Jedis的对应访问接口也相应不用。如何使用Jedis操作两种不同部署方式的Redis数据,以及在web工程里如何快速的切换两种不同的访问方式,是本文要介绍的主要内容。
本示例使用的相关框架版本如下:
Jedis:jedis-2.8.1
spring:spring 4.0.8
涉及的主要类图如下:
JedisClient与JedisClsterClient都实现了IJedisClinet接口,接口里定义了操作redis的各种方法,这两个Client实现类分别对应着单机和集群两种访问方式。RedisOperate类是供其它类调用的Redis操作类,它持有IJedisClient接口的实现类对象,这个对象由spring注入,具体使用哪种连接方式取决于注入的IJedisClient的实现类类型。这里使用的是策略模式。
JedisClusterFactory实现了org.springframework.beans.factory.FactoryBean和org.springframework.beans.factory.InitializingBean接口,用于为JedisClusterClient提供redis.clients.jedis.JedisCluster操作类。JedisClient的操作类是redis.clients.jedis.Jedis,从redis.clients.jedis.JedisPool类中获取。
Spring的配置如下:
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-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-lazy-init="true">
<description>Jedis Configurationdescription>
<context:property-placeholder ignore-unresolvable="true" location="classpath:jeeplus.properties" />
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="300" />
<property name="maxTotal" value="60000" />
<property name="testOnBorrow" value="true" />
bean>
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1" value="${redis.host}" />
<constructor-arg index="2" value="${redis.port}" type="int" />
bean>
<bean name="genericObjectPoolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig">
<property name="maxWaitMillis" value="-1" />
<property name="maxTotal" value="8" />
<property name="minIdle" value="0" />
<property name="maxIdle" value="8" />
bean>
<bean id="jedisCluster" class="com.jeeplus.common.redis.JedisClusterFactory">
<property name="connectionTimeout" value="3000" />
<property name="soTimeout" value="3000" />
<property name="maxRedirections" value="5" />
<property name="genericObjectPoolConfig" ref="genericObjectPoolConfig" />
<property name="jedisClusterNodes">
<set>
<value>127.0.0.1:7000value>
<value>127.0.0.1:7001value>
<value>127.0.0.1:7002value>
set>
property>
bean>
<bean name="redisOperate" class="com.jeeplus.common.redis.RedisOperate">
<property name="jedisClient" ref="jedisClusterClient" />
bean>
beans>
在进行单机、集群切换时,只需要修改 配置即可。
下面看看代码:
IJedisClient
public interface IJedisClient {
public String get(String key);
public Object getObject(String key);
public String set(String key, String value, int cacheSeconds);
public String setObject(String key, Object value, int cacheSeconds);
public List getList(String key);
public List