您的位置:首页 > 数据库 > Redis

spring整合redis做缓存实例

2015-01-13 17:15 549 查看
由于之前写的那个是不经过spring进行整合的redis在java中使用实例,本例是经过spring进行整合的一个redis实例。

可以查看spring官网;spring提供了对jedis的支持,目前已经有spring-data-redis 1.5X的jar包,当然比较稳定的是spring-data-redis 1.4.1
这个版本。本例中用的版本的是最常见的1.10版本的;由于这个demo是maven管理的项目,若是非maven的可以直接去官网下载所需要的jar包.

(1).创建maven工程,并且pom文件中引入相应的jar包

<span style="white-space:pre">	</span><dependencies>
<!--引入spring对reids的支持  -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.0.0.RC1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.35</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
(2) 使用spring整合redis的话,就要用到spring为我们提供的几个类,依次是JedisPoolConfig、JedisConnectionFactory、以及RedisTemplate 这三个类;之前那个demo已经提到过JedisPoolConfig了,这个是jedis连接池的参数配置。

JedisConnectionFactory 类 是jedis连接工厂类,看过里面spring的源码,其实是对jedis 客户端又进行了一层封装的一个工厂类。

RedisTemplate 提供了 获取连接,操作数据,释放连接的 模板化支持;采用RedisCallback来回调业务操作,使得业务代码无需关心 获取连接,归还连接,以及其他异常处理等过程,简化redis操作。

在spring的bean文件中我们要配置上相关的连接参数,以及管理注入依赖的类:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
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/cache http://www.springframework.org/schema/cache/spring-cache.xsd" default-autowire="byName">

<!-- 开启缓存注解 -->
<cache:annotation-driven cache-manager="cacheManager"/>
<!-- jedis 连接池配置参数:  -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxActive" value="100"></property>
<property name="maxIdle" value="25"></property>
<property name="maxWait" value="15000"></property>
<property name="testOnBorrow" value="false"></property>
<property name="testOnReturn" value="false"></property>
</bean>
<!-- jedis 客户端连接工厂 -->
<bean id="jedisConnectionFactory"
class='org.springframework.data.redis.connection.jedis.JedisConnectionFactory'>
<property name="hostName" value="10.224.68.36"/>
<property name="port" value="6379"/>
<property name="poolConfig" ref="poolConfig"/>
<property name="usePool" value="true"/>
</bean>
<!-- redisTemplate  redisTemplate是对Jedis的对redis操作的扩展,有更多的操作,封装使操作更便捷  -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref ="jedisConnectionFactory"/>
<!-- 缓存管理器: 使用redis 当做缓存 -->
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager" c:template-ref ="redisTemplate"/>

</beans>
特别注明一下:这里使用spring提供的缓存管理器,但是前提是要先开启缓存注解;注解才可以被使用。spring提供的缓存注解常用的有三个:@CachePut 、@Cacheable、@CacheEvict

@CachePut 这个注释可以确保方法被执行,同时方法的返回值也被记录到缓存中,实现缓存与数据库的同步更新,

@Cacheable 这个注释:当调用这个方法的时候,会从一个名叫 accountCache 的缓存中查询, 如果没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,否则返回缓存中的对象。

@CacheEvict 注释来标记要清空缓存的方法,当这个方法被调用后,即会清空缓存。

(3) 创建userEntity 和 业务缓存操作层的service,并且提供spring来管理该service

/**
* 用户实体类
* @author leo
*
*/
public class UserEntity {
//用户id
private String userId;
//用户账号
private String EmpCode;
//用户名称
private String EmpName;
//用户角色
private String role;
//职位
private String title;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getEmpCode() {
return EmpCode;
}
public void setEmpCode(String empCode) {
EmpCode = empCode;
}
public String getEmpName() {
return EmpName;
}
public void setEmpName(String empName) {
EmpName = empName;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
UserServiceImpl:

/**
* 业务层接口实现
* @author leo
*
*/
public class UserServiceImpl implements IUserService {

private static final String  cacheKey  ="userEntity";
//日志记录
private static final  Log LOG = LogFactory.getLog(UserServiceImpl.class);

/**
* 新增
* @param entity
* @return
* @CachePut 这个注释可以确保方法被执行,同时方法的返回值也被记录到缓存中,实现缓存与数据库的同步更新。
*/
@CachePut(key ="#entity.userId",value ="entity")
@Override
public void addUserEntity(UserEntity entity) {
//非空
if(entity ==null || StringUtils.isEmpty(entity.getUserId())){
LOG.error("can");
}
/**
* 做数据库持久化,这里就无需再申明了
*/
System.out.println("先插入数据库中,.........");

}

@Override
public void deleteUserEntity(UserEntity entity) {

}
/**
* 根据id 查询
* @return
*  @Cacheable 这个注释:当调用这个方法的时候,会从一个名叫 accountCache 的缓存中查询,
*  如果没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,否则返回缓存中的对象。
*/

@Cacheable(key="#userEntity.userId",value ="userEntity")
@Override
public UserEntity queryUserEntityByUserId(UserEntity userEntity) {
//非空
if(userEntity ==null || StringUtils.isEmpty(userEntity.getUserId())){
return null;
}
//查询数据库,若是缓存中不存在的话 ,会直接查询数据库,
System.out.println("查询数据库");
userEntity.setEmpName("查询数据库的");
return userEntity;
}

}
在spring中添加上

<span style="white-space:pre">		</span><!--  业务层-->
<bean id="userServiceImpl" class="com.deppon.cache.service.impl.UserServiceImpl"/>
(4).spring整合redis 做缓存的实例就可以了,可以写个junit测试类进行测试一下,

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import test.util.SpringTestHelper;

import com.deppon.cache.entity.UserEntity;
import com.deppon.cache.service.IUserService;
import com.deppon.cache.service.impl.UserServiceImpl;

public class TestUserServiceImpl {
/**
* 用户接口
*/
private IUserService userServiceImpl;

public void setUserServiceImpl(IUserService userServiceImpl) {
this.userServiceImpl = userServiceImpl;
}
@Before
public void setUp() throws Exception {
userServiceImpl = (IUserService) SpringTestHelper.get().getBeanByClass(UserServiceImpl.class);
}

@After
public void tearDown() throws Exception {
}
@Test
public void testAddUser(){
UserEntity entity = new UserEntity();
entity.setUserId("000003");
entity.setEmpCode("130566");
entity.setEmpName("leonardo-zeng");
entity.setRole("Java Development Engineer");
entity.setTitle("PM");
userServiceImpl.addUserEntity(entity);
}

@Test
public void testQueryById(){
UserEntity entity = new UserEntity();
entity.setUserId("000003");
UserEntity userEntity =userServiceImpl.queryUserEntityByUserId(entity);
System.out.println(userEntity);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: