由於之前寫的那個是不經過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);
}
}