Jedis与Spring的整合

13 篇文章 0 订阅
11 篇文章 0 订阅

1、spring的基本配置文件bean-base.xml,用于加载properties的配置文件

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	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.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

	<!-- Spring的配置文件 -->
	<!-- 1、读取资源文件 -->
	<!-- 2、<context:property-placeholder /> 底层用的就是下面的bean -->
	<!-- 使用spring自带的占位符替换功能 -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<!-- 允许JVM参数覆盖 -->
		<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
		<!-- 忽略没有找到的资源文件 -->
		<property name="ignoreResourceNotFound" value="true" />
		<!-- 配置资源文件 -->
		<property name="locations">
			<list>
				<value>classpath:redis.properties</value>
			</list>
		</property>
	</bean>


</beans>
2、Spring和redis整合的配置文件,bean-redis.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

	<!--定义连接池的配置 -->
	<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="${redis.maxTotal}" />
	</bean>

	<!--定义Redis的集群信息 -->
	<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
		<!-- 连接池的配置信息 -->
		<constructor-arg index="0" ref="poolConfig" />
		<!-- 主机信息 -->
		<constructor-arg index="1">
			<list>
				<bean class="redis.clients.jedis.JedisShardInfo">
					<constructor-arg index="0" value="${redis.node1.host}" />
					<constructor-arg index="1" value="${redis.node1.port}" />
					<property name="password" value="${redis.node1.password}" />
				</bean>
				<bean class="redis.clients.jedis.JedisShardInfo">
					<constructor-arg index="0" value="${redis.node2.host}" />
					<constructor-arg index="1" value="${redis.node2.port}" />
					<property name="password" value="${redis.node2.password}" />
				</bean>

			</list>
		</constructor-arg>
	</bean>

	<!-- -->
	<context:component-scan base-package="cn.spring.redis" />

</beans>

3、redis相关的配置,redis.properties

redis.maxTotal=50
redis.node1.host=192.168.2.111
redis.node1.port=6379
redis.node1.password=123456

redis.node2.host=192.168.2.116
redis.node2.port=6380
redis.node2.password=123456
4、log4j日志的配置文件,log4j.properties

log4j.rootLogger=DEBUG,A1
log4j.logger.org.clients = DEBUG

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n
5、用于操作Redis数据库,简单的封装

import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class RedisServiceSimple {
	@Autowired(required = false)
	private ShardedJedisPool shardedJedisPool;

	public String set(String key, String value) {
		ShardedJedis shardedJedis = null;
		try {
			// 从连接池中获取到jedis分片对象
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.set(key, value);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != shardedJedis) {
				// 关闭,检测连接是否有效,有效则放回到连接池中,无效则重置状态
				shardedJedis.close();
			}
		}
		return null;
	}

	public String get(String key) {
		ShardedJedis shardedJedis = null;
		try {
			// 从连接池中获取到jedis分片对象
			shardedJedis = shardedJedisPool.getResource();
			return shardedJedis.get(key);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != shardedJedis) {
				// 关闭,检测连接是否有效,有效则放回到连接池中,无效则重置状态
				shardedJedis.close();
			}
		}
		return null;
	}
}

6、使用模板方法,回调函数的方式进行处理

      6.1 定义接口,用于执行具体的方法逻辑

/**
 * 
 * @param <E>
 *            代表输入
 * @param <T>
 *            代表输出
 */
public interface Function<E, T> {
	public T callBack(E e);
}

      6.2 Redis工具类的封装,模板方法

// 封装通用逻辑
	private <T> T execute(Function<ShardedJedis, T> fun) {
		ShardedJedis shardedJedis = null;
		try {
			// 从连接池中获取到jedis分片对象
			shardedJedis = shardedJedisPool.getResource();
			return fun.callBack(shardedJedis);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != shardedJedis) {
				// 关闭,检测连接是否有效,有效则放回到连接池中,无效则重置状态
				shardedJedis.close();
			}
		}
		return null;
	}

      6.3 Redis工具类封装的具体实现

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

@Service
public class RedisService {
	@Autowired(required = false)
	private ShardedJedisPool shardedJedisPool;

	// 封装通用逻辑
	private <T> T execute(Function<ShardedJedis, T> fun) {
		ShardedJedis shardedJedis = null;
		try {
			// 从连接池中获取到jedis分片对象
			shardedJedis = shardedJedisPool.getResource();
			return fun.callBack(shardedJedis);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != shardedJedis) {
				// 关闭,检测连接是否有效,有效则放回到连接池中,无效则重置状态
				shardedJedis.close();
			}
		}
		return null;
	}

	/**
	 * 执行set方法
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public String set(final String key, final String value) {
		return this.execute(new Function<ShardedJedis, String>() {
			@Override
			public String callBack(ShardedJedis shardedJedis) {
				return shardedJedis.set(key, value);
			}
		});
	}

	/**
	 * 执行set方法,并设置生存时间
	 * 
	 * @param key
	 * @param value
	 * @param seconds
	 *            时间,单位是秒
	 * @return
	 */
	public String set(final String key, final String value,
			final Integer seconds) {
		return this.execute(new Function<ShardedJedis, String>() {
			@Override
			public String callBack(ShardedJedis shardedJedis) {
				String str = shardedJedis.set(key, value);
				shardedJedis.expire(key, seconds);
				return str;
			}
		});
	}

	/**
	 * 执行get方法
	 * 
	 * @param key
	 * @return
	 */
	public String get(final String key) {
		return this.execute(new Function<ShardedJedis, String>() {
			@Override
			public String callBack(ShardedJedis shardedJedis) {
				return shardedJedis.get(key);
			}
		});
	}

	/**
	 * 删除key
	 * 
	 * @param key
	 * @return
	 */
	public Long del(final String key) {
		return this.execute(new Function<ShardedJedis, Long>() {
			@Override
			public Long callBack(ShardedJedis shardedJedis) {
				return shardedJedis.del(key);
			}
		});
	}

	/**
	 * 设置生存时间
	 * 
	 * @param key
	 * @param seconds
	 * @return
	 */
	public Long expire(final String key, final int seconds) {
		return this.execute(new Function<ShardedJedis, Long>() {
			@Override
			public Long callBack(ShardedJedis shardedJedis) {
				return shardedJedis.expire(key, seconds);
			}
		});
	}

}

7、测试

      7.1 测试代码

public class RedisSpringTest {

	@Test
	public void test01() {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"classpath:spring/bean-*.xml");
		RedisService redisService = context.getBean("redisService",
				RedisService.class);
		for (int i = 0; i < 100; i++) {
			redisService.set("key" + i, "value" + i);
		}
		System.out.println(redisService.get("key10"));

	}
}

      7.2 运行结果

           

8、源码下载


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值