本章我们将实例讲解Redis如何与Spring整合。由于Redis与Spring的整合手段比较多,本章将着重讲解Spring与Spring-data-redis整合。
实例
新建Maven web项目,并将指定build path source folder。
项目结构
- Customize build path source folder。
- 文件代码
- pom.xml
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.sstps.oscar
Template2
0.0.1-SNAPSHOT
UTF-8
org.springframework.data
spring-data-redis
1.0.2.RELEASE
org.springframework
spring-core
3.1.2.RELEASE
redis.clients
jedis
2.1.0
commons-logging
commons-logging
1.1.1
provided
- redis.properties
redis.host=127.0.0.1
redis.port=6379
redis.pass=wljr
redis.timeout=3000
redis.maxIdle=300
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true
- AplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
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-3.1.xsd">
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
- UserDao.java
package com.x.redis.dao;
import com.x.redis.pojo.User;
public interface UserDao {
public void saveUser(final User user);
public User getUser(final long id);
}
- User.java
package com.x.redis.pojo;
public class User {
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- UserDaoImpl.java
package com.x.redis.dao.imp;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import com.x.redis.dao.UserDao;
import com.x.redis.pojo.User;
public class UserDAOImpl implements UserDao {
public void saveUser(final User user) {
redisTemplate.execute(new RedisCallback() {
@Override
public Object doInRedis(RedisConnection connection) throws DataAccessException {
connection.set(redisTemplate.getStringSerializer().serialize("user.uid." + user.getId()),
redisTemplate.getStringSerializer().serialize(user.getName()));
return null;
}
});
}
@Override
public User getUser(final long id) {
return redisTemplate.execute(new RedisCallback() {
@Override
public User doInRedis(RedisConnection connection) throws DataAccessException {
byte[] key = redisTemplate.getStringSerializer().serialize("user.uid." + id);
if (connection.exists(key)) {
byte[] value = connection.get(key);
String name = redisTemplate.getStringSerializer().deserialize(value);
User user = new User();
user.setName(name);
user.setId(id);
return user;
}
return null;
}
});
}
}
- Template.java
package com.x.redis.template;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.x.redis.dao.imp.UserDAOImpl;
import com.x.redis.pojo.User;
public class Temolate {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:/AplicationContex.xml");
UserDAOImpl userDAOImpl = (UserDAOImpl) ac.getBean("userDAO");
User user1 = new User();
user1.setId(1);
user1.setName("Hi~Redis");
userDAOImpl.saveUser(user1);
User user2 = userDAOImpl.getUser(1);
System.out.println(user2.getName());
}
}
运行结果:
总结
总的来说Spring+Spring-data-redis整合算是一种比较官方比较主流的方式,下面我们总结一下Spring+Spring-data-redis整合的优缺点:
- 缺点
对Jedispool的封装过于完美以至于当完美需要灵活使用jedispool的时候无法自定义。
RedisCliTemplate想对较复杂,而且每次要获得RedisClientTemplate有需要RedisConnection的协助,这点在UserDaoImpl.java的两个方法中提现地尤为突出。
…..
- 优点
配置优雅,封装集成度高。
….
Redis 讲解系列之 与Spring集成(二)
上章中我们讲解了如何使用spring与spring-data-redis如何整合在一起同时总结出了一些优缺点,正对于缺点的优化和改善,本章将讲解一种高自定获取Jedispool和RedisClientTemplate的方法。
实例
新建Maven web项目,并自定义Build path source folde。
文件代码
- pom.xml
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.sstps.redis
Template1
0.0.1-SNAPSHOT
war
UTF-8
org.springframework.data
spring-data-redis
1.0.2.RELEASE
org.springframework
spring-core
3.1.2.RELEASE
org.springframework
spring-web
3.1.2.RELEASE
redis.clients
jedis
2.4.2
commons-logging
commons-logging
1.1.1
provided
- redis.properties
# Redis settings
redis.host=127.0.0.1
redis.port=6379
redis.password=wljr
redis.timeout=3000
redis.maxIdle=300
redis.maxTotal=600
redis.maxWait=1000
redis.testOnBorrow=true
redis.testOnReturn=true
- AplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
/WEB-INF/classes/redis.properties
- RedisDataSource.java
- package com.sstps.redis;
- import redis.clients.jedis.Jedis;
- public interface RedisDataSource {
- // 取得redis的客户端,可以执行命令了。
- public abstract Jedis getRedisClient();
- //将资源返还给pool
- public void returnResource(Jedis shardedJedis);
- //出现异常后,将资源返还给pool
- public void returnResource(Jedis shardedJedis,boolean broken);
- }
- RedisDataSourceImpl.java
- package com.sstps.redis;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import redis.clients.jedis.Jedis;
- import redis.clients.jedis.JedisPool;
- public class RedisDataSourceImpl implements RedisDataSource {
- public static Log log = LogFactory.getLog(RedisDataSourceImpl.class);
- private JedisPool jedisPool;
- public JedisPool getJedisPool() {
- return jedisPool;
- }
- public void setJedisPool(JedisPool JedisPool) {
- this.jedisPool = JedisPool;
- }
- public Jedis getRedisClient() {
- try {
- Jedis shardJedis = jedisPool.getResource();
- return shardJedis;
- } catch (Exception e) {
- log.error("getRedisClent error", e);
- }
- return null;
- }
- public void returnResource(Jedis Jedis) {
- jedisPool.returnResource(Jedis);
- }
- public void returnResource(Jedis Jedis, boolean broken) {
- if (broken) {
- jedisPool.returnBrokenResource(Jedis);
- } else {
- jedisPool.returnResource(Jedis);
- }
- }
- }
- Template.java
- package com.sstps.template;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.sstps.redis.RedisClientTemplate;
- public class Template {
- public static void main(String[] args) {
- ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:/AplicationContext.xml");
- RedisClientTemplate redisClient = (RedisClientTemplate)ac.getBean("redisClientTemplate");
- redisClient.set("a", "Hi~Redis");
- System.out.println(redisClient.get("a"));
- }
- }
- RedisClientTemplate.java
总结
Redis与Spring直接整合,而对RedisClientTemplate和JedisPool做了剥离和二次封装。下面我们总结一下本章方法的优缺点:
缺点
代码较冗余,毕竟是二次封装,从RedisClientTemplate.java即可看出。
…..
-
优点
使用体验极好,不要考虑考虑新建或者归还jedispool的问题。使用时直接使用RedisClientTemplate即可。
优化点
考虑将本章例子的Redis打成jar包已依赖的方式导入,然后在AplictionContext.xml完成同样的配置,这样依赖代码既不冗余,灵活性和实用性极高了。