標籤:

Spring如何與redis進行整合開發?


提供一個網上的例子,我進行了測試,沒問題

Spring 整合 Redis

資源:spring+redis整合demo

applicationContext.xml

&
&

&

&
&


&


&


&


&

&

&
&


&

&
&

redis.properties

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

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

UserDao.java

package com.x.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.Assert;

import com.x.dao.AbstractBaseRedisDao;
import com.x.dao.IUserDao;
import com.x.entity.User;

/**
* Dao
* @author http://blog.csdn.net/java2000_wl
* @version &1.0&
*/
public class UserDao extends AbstractBaseRedisDao& implements IUserDao {

/**
* 新增
*&------------------------------&
* @param user
* @return
*/
public boolean add(final User user) {
boolean result = redisTemplate.execute(new RedisCallback&() {
public Boolean doInRedis(RedisConnection connection)
throws DataAccessException {
RedisSerializer& serializer = getRedisSerializer();
byte[] key = serializer.serialize(user.getId());
byte[] name = serializer.serialize(user.getName());
return connection.setNX(key, name);
}
});
return resu< } /** * 批量新增 使用pipeline方式 *&------------------------------&
*@param list
*@return
*/
public boolean add(final List& list) {
Assert.notEmpty(list);
boolean result = redisTemplate.execute(new RedisCallback&() {
public Boolean doInRedis(RedisConnection connection)
throws DataAccessException {
RedisSerializer& serializer = getRedisSerializer();
for (User user : list) {
byte[] key = serializer.serialize(user.getId());
byte[] name = serializer.serialize(user.getName());
connection.setNX(key, name);
}
return true;
}
}, false, true);
return resu< } /** * 刪除 * &------------------------------&
* @param key
*/
public void delete(String key) {
List& list = new ArrayList&();
list.add(key);
delete(list);
}

/**
* 刪除多個
* &------------------------------&
* @param keys
*/
public void delete(List& keys) {
redisTemplate.delete(keys);
}

/**
* 修改
* &------------------------------&
* @param user
* @return
*/
public boolean update(final User user) {
String key = user.getId();
if (get(key) == null) {
throw new NullPointerException("數據行不存在, key = " + key);
}
boolean result = redisTemplate.execute(new RedisCallback&() {
public Boolean doInRedis(RedisConnection connection)
throws DataAccessException {
RedisSerializer& serializer = getRedisSerializer();
byte[] key = serializer.serialize(user.getId());
byte[] name = serializer.serialize(user.getName());
connection.set(key, name);
return true;
}
});
return resu< } /** * 通過key獲取 * &------------------------------&
* @param keyId
* @return
*/
public User get(final String keyId) {
User result = redisTemplate.execute(new RedisCallback&() {
public User doInRedis(RedisConnection connection)
throws DataAccessException {
RedisSerializer& serializer = getRedisSerializer();
byte[] key = serializer.serialize(keyId);
byte[] value = connection.get(key);
if (value == null) {
return null;
}
String name = serializer.deserialize(value);
return new User(keyId, name, null);
}
});
return resu< } }

AbstractBaseRedisDao.java

package com.x.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
* AbstractBaseRedisDao
* @author http://blog.csdn.net/java2000_wl
* @version &1.0&
*/
public abstract class AbstractBaseRedisDao& {

@Autowired
protected RedisTemplate& redisTemplate;

/**
* 設置redisTemplate
* @param redisTemplate the redisTemplate to set
*/
public void setRedisTemplate(RedisTemplate& redisTemplate) {
this.redisTemplate = redisTemplate;
}

/**
* 獲取 RedisSerializer
* &------------------------------&
*/
protected RedisSerializer& getRedisSerializer() {
return redisTemplate.getStringSerializer();
}
}

IUserDao.java

package com.x.dao;

import java.util.List;

import com.x.entity.User;

/**
* @author http://blog.csdn.net/java2000_wl
* @version &1.0&
*/
public interface IUserDao {

/**
* 新增
* &------------------------------&
* @param user
* @return
*/
boolean add(User user);

/**
* 批量新增 使用pipeline方式
* &------------------------------&
* @param list
* @return
*/
boolean add(List& list);

/**
* 刪除
* &------------------------------&
* @param key
*/
void delete(String key);

/**
* 刪除多個
* &------------------------------&
* @param keys
*/
void delete(List& keys);

/**
* 修改
* &------------------------------&
* @param user
* @return
*/
boolean update(User user);

/**
* 通過key獲取
* &------------------------------&
* @param keyId
* @return
*/
User get(String keyId);
}

User.java

package com.x.entity;

import java.io.Serializable;

/**
* @author http://blog.csdn.net/java2000_wl
* @version &1.0&
*/
public class User implements Serializable {

private static final long serialVersionUID = -6011241820070393952L;

private String id;

private String name;

private String password;

/**
* &------------------------------&
*/
public User() {

}

/**
* &------------------------------&
*/
public User(String id, String name, String password) {
super();
this.id = id;
this.name = name;
this.password = password;
}

/**
* 獲得id
* @return the id
*/
public String getId() {
return id;
}

/**
* 設置id
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}

/**
* 獲得name
* @return the name
*/
public String getName() {
return name;
}

/**
* 設置name
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}

/**
* 獲得password
* @return the password
*/
public String getPassword() {
return password;
}

/**
* 設置password
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
}

---------------------------------------------------------------------

再提供一個例子,也是網路上的,僅僅使用了jedisConnectionFactory類直接獲取Jedis對象

package com.mkfree.redis.test;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

import redis.clients.jedis.Jedis;

/**
* 封裝redis 緩存伺服器服務介面
*
* @author hk http://blog.csdn.net/sunny243788557/article/details/34431357
* 2012-12-16 上午3:09:18
*/
public class RedisService {

/**
* 通過key刪除(位元組)
*
* @param key
*/
public void del(byte[] key) {
this.getJedis().del(key);
}

/**
* 通過key刪除
*
* @param key
*/
public void del(String key) {
this.getJedis().del(key);
}

/**
* 添加key value 並且設置存活時間(byte)
*
* @param key
* @param value
* @param liveTime
*/
public void set(byte[] key, byte[] value, int liveTime) {
this.set(key, value);
this.getJedis().expire(key, liveTime);
}

/**
* 添加key value 並且設置存活時間
*
* @param key
* @param value
* @param liveTime
*/
public void set(String key, String value, int liveTime) {
this.set(key, value);
this.getJedis().expire(key, liveTime);
}

/**
* 添加key value
*
* @param key
* @param value
*/
public void set(String key, String value) {
this.getJedis().set(key, value);
}

/**
* 添加key value (位元組)(序列化)
*
* @param key
* @param value
*/
public void set(byte[] key, byte[] value) {
this.getJedis().set(key, value);
}

/**
* 獲取redis value (String)
*
* @param key
* @return
*/
public String get(String key) {
String value = this.getJedis().get(key);
return value;
}

/**
* 獲取redis value (byte [] )(反序列化)
*
* @param key
* @return
*/
public byte[] get(byte[] key) {
return this.getJedis().get(key);
}

/**
* 通過正則匹配keys
*
* @param pattern
* @return
*/
public Set& keys(String pattern) {
return this.getJedis().keys(pattern);
}

/**
* 檢查key是否已經存在
*
* @param key
* @return
*/
public boolean exists(String key) {
return this.getJedis().exists(key);
}

/**
* 清空redis 所有數據
*
* @return
*/
public String flushDB() {
return this.getJedis().flushDB();
}

/**
* 查看redis里有多少數據
*/
public long dbSize() {
return this.getJedis().dbSize();
}

/**
* 檢查是否連接成功
*
* @return
*/
public String ping() {
return this.getJedis().ping();
}

/**
* 獲取一個jedis 客戶端
*
* @return
*/
private Jedis getJedis() {
if (jedis == null) {
return jedisConnectionFactory.getShardInfo().createResource();
}
return jedis;
}

private RedisService() {

}

// 操作redis客戶端
private static Jedis jedis;
@Autowired
@Qualifier("jedisConnectionFactory")
private JedisConnectionFactory jedisConnectionFactory;
}

package com.mkfree.redis.test;

import java.util.Set;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* redis spring 簡單例子
*
* @author hk http://blog.csdn.net/sunny243788557/article/details/34431357
* 2012-12-22 上午10:40:15
*/
public class TestRedis {

public static void main(String[] args) throws InterruptedException {
ApplicationContext app = new ClassPathXmlApplicationContext(
"classpath:spring-context.xml");
// 這裡已經配置好,屬於一個redis的服務介面
RedisService redisService = (RedisService) app.getBean("redisService");

String ping = redisService.ping();// 測試是否連接成功,連接成功輸出PONG
System.out.println(ping);

// 清空reids所有數據
redisService.flushDB();

// 首先,我們看下redis服務里是否有數據
long dbSizeStart = redisService.dbSize();
System.out.println(dbSizeStart);

redisService.set("username", "oyhk");// 設值(查看了源代碼,默認存活時間30分鐘)
String username = redisService.get("username");// 取值
System.out.println(username);

redisService.set("username1", "oyhk1", 1);// 設值,並且設置數據的存活時間(這裡以秒為單位)
String username1 = redisService.get("username1");
System.out.println(username1);

Thread.sleep(2000);// 我睡眠一會,再去取,這個時間超過了,他的存活時間

String liveUsername1 = redisService.get("username1");
System.out.println(liveUsername1);// 輸出null

// 是否存在
boolean exist = redisService.exists("username");
System.out.println(exist);

// 查看keys
Set& keys = redisService.keys("*");// 這裡查看所有的keys
System.out.println(keys);// 只有username username1(已經清空了)

// 刪除
redisService.set("username2", "oyhk2");
String username2 = redisService.get("username2");
System.out.println(username2);
redisService.del("username2");
String username2_2 = redisService.get("username2");
System.out.println(username2_2);// 如果為null,那麼就是刪除數據了

// dbsize
long dbSizeEnd = redisService.dbSize();
System.out.println(dbSizeEnd);

}
}

&
&

&
&
&
&

&
&

&
&

&

&

2016-2-25 11:11:45 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@14d3343: startup date [Thu Feb 25 11:11:45 CST 2016]; root of context hierarchy
2016-2-25 11:11:45 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-context.xml]
2016-2-25 11:11:47 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@12a3722: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,jedisConnectionFactory,redisService]; root of factory hierarchy
PONG
0
oyhk
oyhk1
null
true
[username]
oyhk2
null
1


請參考如下代碼

spring項目整合ehcache和redis緩存實例

Spring MVC+Freemarker+Bootstrap整合實現spring-data-redis增刪改查的入門學習實例

ssm使用redis做為spring+spring MVC+mybatis整合的二級緩存,基於maven搭建

ssm使用redis做為spring+spring MVC+mybatis整合的二級緩存

springdata redis實現的簡單demo

搜索redis的分享列表-分享-最代碼


推薦閱讀:

Start of spring and Spring Festival
初識Spring ^_^ !
Spring中Transactional註解的實現
Struts2.1.6與Spring2.5.6框架整合
Spring RestTemplate作為負載平衡器客戶端

TAG:Redis | Spring |