spring整合redis_Redis 讲解系列之 与Spring集成

本章我们将实例讲解Redis如何与Spring整合。由于Redis与Spring的整合手段比较多,本章将着重讲解Spring与Spring-data-redis整合。

实例

新建Maven web项目,并将指定build path source folder。

项目结构

b92e636abe5f2a48951a032c8837b882.png
  • Customize build path source folder。
a8abb4a2867939d99f7ec7477624168a.png
  • 文件代码
  • 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());
    }
}

运行结果:

e88c6a39f9be8b8f957cd9f5042774b2.png

总结

总的来说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。

e8900f196df2f2422b9f12fe4e2888fc.png

文件代码

  • 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
  1. package com.sstps.redis;
  2. import redis.clients.jedis.Jedis;
  3. public interface RedisDataSource {
  4. // 取得redis的客户端,可以执行命令了。
  5. public abstract Jedis getRedisClient();
  6. //将资源返还给pool
  7. public void returnResource(Jedis shardedJedis);
  8. //出现异常后,将资源返还给pool
  9. public void returnResource(Jedis shardedJedis,boolean broken);
  10. }
  • RedisDataSourceImpl.java
  1. package com.sstps.redis;
  2. import org.apache.commons.logging.Log;
  3. import org.apache.commons.logging.LogFactory;
  4. import redis.clients.jedis.Jedis;
  5. import redis.clients.jedis.JedisPool;
  6. public class RedisDataSourceImpl implements RedisDataSource {
  7. public static Log log = LogFactory.getLog(RedisDataSourceImpl.class);
  8. private JedisPool jedisPool;
  9. public JedisPool getJedisPool() {
  10. return jedisPool;
  11. }
  12. public void setJedisPool(JedisPool JedisPool) {
  13. this.jedisPool = JedisPool;
  14. }
  15. public Jedis getRedisClient() {
  16. try {
  17. Jedis shardJedis = jedisPool.getResource();
  18. return shardJedis;
  19. } catch (Exception e) {
  20. log.error("getRedisClent error", e);
  21. }
  22. return null;
  23. }
  24. public void returnResource(Jedis Jedis) {
  25. jedisPool.returnResource(Jedis);
  26. }
  27. public void returnResource(Jedis Jedis, boolean broken) {
  28. if (broken) {
  29. jedisPool.returnBrokenResource(Jedis);
  30. } else {
  31. jedisPool.returnResource(Jedis);
  32. }
  33. }
  34. }
  • Template.java
  1. package com.sstps.template;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. import com.sstps.redis.RedisClientTemplate;
  5. public class Template {
  6. public static void main(String[] args) {
  7. ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:/AplicationContext.xml");
  8. RedisClientTemplate redisClient = (RedisClientTemplate)ac.getBean("redisClientTemplate");
  9. redisClient.set("a", "Hi~Redis");
  10. System.out.println(redisClient.get("a"));
  11. }
  12. }
  • RedisClientTemplate.java

总结

Redis与Spring直接整合,而对RedisClientTemplate和JedisPool做了剥离和二次封装。下面我们总结一下本章方法的优缺点:

缺点

代码较冗余,毕竟是二次封装,从RedisClientTemplate.java即可看出。

…..

-

优点

使用体验极好,不要考虑考虑新建或者归还jedispool的问题。使用时直接使用RedisClientTemplate即可。

优化点

考虑将本章例子的Redis打成jar包已依赖的方式导入,然后在AplictionContext.xml完成同样的配置,这样依赖代码既不冗余,灵活性和实用性极高了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值