日期:2014-05-16  浏览次数:20490 次

spring 整合redis

pom构建:

?

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.x.redis</groupId>
  <artifactId>springredis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
  	<dependency>
  		<groupId>org.springframework.data</groupId>
  		<artifactId>spring-data-redis</artifactId>
  		<version>1.0.2.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-test</artifactId>
  		<version>3.1.2.RELEASE</version>
  		<scope>test</scope>
  	</dependency>
  	
  	<dependency>
  		<groupId>redis.clients</groupId>
  		<artifactId>jedis</artifactId>
  		<version>2.1.0</version>
  	</dependency>
  	
  	 <dependency>
  		<groupId>junit</groupId>
  		<artifactId>junit</artifactId>
  		<version>4.8.2</version>
  		<scope>test</scope>
  	</dependency>
  </dependencies>


spring配置文件(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:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<context:property-placeholder location="classpath:redis.properties" />

	<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxIdle" value="${redis.maxIdle}" />
		<property name="maxActive" value="${redis.maxActive}" />
		<property name="maxWait" value="${redis.maxWait}" />
		<property name="testOnBorrow" value="${redis.testOnBorrow}" />
	</bean>
	
	<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
		p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"  p:pool-config-ref="poolConfig"/>
	
	<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
		<property name="connectionFactory" 	ref="connectionFactory" />
	</bean>		
	
	<bean id="userDao" class="com.x.dao.impl.UserDao" /> 
</beans>

redis.properties

?

?

# Redis settings
redis.host=localhost
redis.port=6379
redis.pass=java2000_wl


redis.maxIdle=300
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true

?

java代码:

?

package com.x.entity;

import java.io.Serializable;

/** 
 * @author http://blog.csdn.net/java2000_wl 
 * @version <b>1.0</b> 
 */ 
public class User implements Serializable {
	
	private static fina