Redis之——Spring整合Redis

来源:互联网 发布:上海淘宝科技有限公司 编辑:程序博客网 时间:2024/06/01 08:49
做过大型软件系统的同学都知道,随着系统数据越来越庞大,越来越复杂,随之带来的问题就是系统性能越来越差,尤其是频繁操作数据库带来的性能损耗更为严重。很多业绩大牛为此提出了众多的解决方案和开发了很多框架以优化这种频繁操作数据库所带来的性能损耗,其中,尤为突出的两个缓存服务器是Memcached和Redis。今天,我们不讲Memcached和Redis本身,这里主要为大家介绍如何使spring与Redis整合。有关Memcached与Spring整合的博文请参见《Memcached之——整合Spring完整示例》。好,我们进入正文:

1、pom构建

[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  2.   
  3.   <modelVersion>4.0.0</modelVersion>  
  4.   <groupId>com.x.redis</groupId>  
  5.   <artifactId>springredis</artifactId>  
  6.   <version>0.0.1-SNAPSHOT</version>  
  7.     
  8.   <dependencies>  
  9.     <dependency>  
  10.         <groupId>org.springframework.data</groupId>  
  11.         <artifactId>spring-data-redis</artifactId>  
  12.         <version>1.0.2.RELEASE</version>  
  13.     </dependency>  
  14.     <dependency>  
  15.         <groupId>org.springframework</groupId>  
  16.         <artifactId>spring-test</artifactId>  
  17.         <version>3.1.2.RELEASE</version>  
  18.         <scope>test</scope>  
  19.     </dependency>  
  20.       
  21.     <dependency>  
  22.         <groupId>redis.clients</groupId>  
  23.         <artifactId>jedis</artifactId>  
  24.         <version>2.1.0</version>  
  25.     </dependency>  
  26.       
  27.      <dependency>  
  28.         <groupId>junit</groupId>  
  29.         <artifactId>junit</artifactId>  
  30.         <version>4.8.2</version>  
  31.         <scope>test</scope>  
  32.     </dependency>  
  33.   </dependencies>  
  34. </project>  

2、spring配置文件(applicationContext.xml)

[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:aop="http://www.springframework.org/schema/aop"  
  7.     xsi:schemaLocation="  
  8.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  9.             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  
  10.   
  11.     <context:property-placeholder location="classpath:redis.properties" />  
  12.   
  13.     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
  14.         <property name="maxIdle" value="${redis.maxIdle}" />  
  15.         <property name="maxActive" value="${redis.maxActive}" />  
  16.         <property name="maxWait" value="${redis.maxWait}" />  
  17.         <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
  18.     </bean>  
  19.       
  20.     <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
  21.         p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"  p:pool-config-ref="poolConfig"/>  
  22.       
  23.     <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
  24.         <property name="connectionFactory"   ref="connectionFactory" />  
  25.     </bean>         
  26.       
  27.     <bean id="userDao" class="com.lyz.dao.impl.UserDaoImpl" />   
  28. </beans>  

3、redis.properties

[plain] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. # Redis settings  
  2. redis.host=192.168.157.130  
  3. redis.port=6379  
  4. redis.pass=liuyazhuang  
  5.   
  6.   
  7. redis.maxIdle=300  
  8. redis.maxActive=600  
  9. redis.maxWait=1000  
  10. redis.testOnBorrow=true  

4、User实体类

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.lyz.entity;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. /** 
  6.  * user实体类 
  7.  * @author liuyazhuang 
  8.  * 
  9.  */  
  10. public class User implements Serializable {  
  11.       
  12.     private static final long serialVersionUID = -6011241820070393952L;  
  13.   
  14.     private String id;  
  15.       
  16.     private String name;  
  17.       
  18.     private String password;  
  19.   
  20.     /** 
  21.      * <br>------------------------------<br> 
  22.      */  
  23.     public User() {  
  24.           
  25.     }  
  26.       
  27.     /** 
  28.      * <br>------------------------------<br> 
  29.      */  
  30.     public User(String id, String name, String password) {  
  31.         super();  
  32.         this.id = id;  
  33.         this.name = name;  
  34.         this.password = password;  
  35.     }  
  36.   
  37.     /** 
  38.      * 获得id 
  39.      * @return the id 
  40.      */  
  41.     public String getId() {  
  42.         return id;  
  43.     }  
  44.   
  45.     /** 
  46.      * 设置id 
  47.      * @param id the id to set 
  48.      */  
  49.     public void setId(String id) {  
  50.         this.id = id;  
  51.     }  
  52.   
  53.     /** 
  54.      * 获得name 
  55.      * @return the name 
  56.      */  
  57.     public String getName() {  
  58.         return name;  
  59.     }  
  60.   
  61.     /** 
  62.      * 设置name 
  63.      * @param name the name to set 
  64.      */  
  65.     public void setName(String name) {  
  66.         this.name = name;  
  67.     }  
  68.   
  69.     /** 
  70.      * 获得password 
  71.      * @return the password 
  72.      */  
  73.     public String getPassword() {  
  74.         return password;  
  75.     }  
  76.   
  77.     /** 
  78.      * 设置password 
  79.      * @param password the password to set 
  80.      */  
  81.     public void setPassword(String password) {  
  82.         this.password = password;  
  83.     }  
  84. }  

5、User操作的接口IUserDao

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.lyz.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.lyz.entity.User;  
  6.    
  7. /** 
  8.  * user操作接口 
  9.  * @author liuyazhuang 
  10.  * 
  11.  */  
  12. public interface IUserDao {  
  13.       
  14.     /** 
  15.      * 新增 
  16.      * <br>------------------------------<br> 
  17.      * @param user 
  18.      * @return 
  19.      */  
  20.     boolean add(User user);  
  21.       
  22.     /** 
  23.      * 批量新增 使用pipeline方式 
  24.      * <br>------------------------------<br> 
  25.      * @param list 
  26.      * @return 
  27.      */  
  28.     boolean add(List<User> list);  
  29.       
  30.     /** 
  31.      * 删除 
  32.      * <br>------------------------------<br> 
  33.      * @param key 
  34.      */  
  35.     void delete(String key);  
  36.       
  37.     /** 
  38.      * 删除多个 
  39.      * <br>------------------------------<br> 
  40.      * @param keys 
  41.      */  
  42.     void delete(List<String> keys);  
  43.       
  44.     /** 
  45.      * 修改 
  46.      * <br>------------------------------<br> 
  47.      * @param user 
  48.      * @return  
  49.      */  
  50.     boolean update(User user);  
  51.   
  52.     /** 
  53.      * 通过key获取 
  54.      * <br>------------------------------<br> 
  55.      * @param keyId 
  56.      * @return  
  57.      */  
  58.     User get(String keyId);  
  59. }  

6、基本的抽象类

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.lyz.dao.impl;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.data.redis.core.RedisTemplate;  
  5. import org.springframework.data.redis.serializer.RedisSerializer;  
  6.   
  7.   
  8. /** 
  9.  * 基本的抽象类 
  10.  * @author liuyazhuang 
  11.  * 
  12.  * @param <K> 
  13.  * @param <V> 
  14.  */  
  15. public abstract class AbstractBaseRedisDao<K, V> {  
  16.       
  17.     @Autowired  
  18.     protected RedisTemplate<K, V> redisTemplate;  
  19.   
  20.     /** 
  21.      * 设置redisTemplate 
  22.      * @param redisTemplate the redisTemplate to set 
  23.      */  
  24.     public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {  
  25.         this.redisTemplate = redisTemplate;  
  26.     }  
  27.       
  28.     /** 
  29.      * 获取 RedisSerializer 
  30.      * <br>------------------------------<br> 
  31.      */  
  32.     protected RedisSerializer<String> getRedisSerializer() {  
  33.         return redisTemplate.getStringSerializer();  
  34.     }  
  35. }  

7、IUserDao的实现类UserDaoImpl

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.lyz.dao.impl;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.springframework.dao.DataAccessException;  
  7. import org.springframework.data.redis.connection.RedisConnection;  
  8. import org.springframework.data.redis.core.RedisCallback;  
  9. import org.springframework.data.redis.serializer.RedisSerializer;  
  10. import org.springframework.util.Assert;  
  11.   
  12. import com.lyz.dao.IUserDao;  
  13. import com.lyz.entity.User;  
  14.   
  15.    
  16. /** 
  17.  *  接口的实现类 
  18.  * @author liuyazhuang 
  19.  * 
  20.  */  
  21. public class UserDaoImpl extends AbstractBaseRedisDao<String, User> implements IUserDao {  
  22.   
  23.     /**  
  24.      * 新增 
  25.      *<br>------------------------------<br> 
  26.      * @param user 
  27.      * @return 
  28.      */  
  29.     public boolean add(final User user) {  
  30.         boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
  31.             public Boolean doInRedis(RedisConnection connection)  
  32.                     throws DataAccessException {  
  33.                 RedisSerializer<String> serializer = getRedisSerializer();  
  34.                 byte[] key  = serializer.serialize(user.getId());  
  35.                 byte[] name = serializer.serialize(user.getName());  
  36.                 return connection.setNX(key, name);  
  37.             }  
  38.         });  
  39.         return result;  
  40.     }  
  41.       
  42.     /** 
  43.      * 批量新增 使用pipeline方式   
  44.      *<br>------------------------------<br> 
  45.      *@param list 
  46.      *@return 
  47.      */  
  48.     public boolean add(final List<User> list) {  
  49.         Assert.notEmpty(list);  
  50.         boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
  51.             public Boolean doInRedis(RedisConnection connection)  
  52.                     throws DataAccessException {  
  53.                 RedisSerializer<String> serializer = getRedisSerializer();  
  54.                 for (User user : list) {  
  55.                     byte[] key  = serializer.serialize(user.getId());  
  56.                     byte[] name = serializer.serialize(user.getName());  
  57.                     connection.setNX(key, name);  
  58.                 }  
  59.                 return true;  
  60.             }  
  61.         }, falsetrue);  
  62.         return result;  
  63.     }  
  64.       
  65.     /**  
  66.      * 删除 
  67.      * <br>------------------------------<br> 
  68.      * @param key 
  69.      */  
  70.     public void delete(String key) {  
  71.         List<String> list = new ArrayList<String>();  
  72.         list.add(key);  
  73.         delete(list);  
  74.     }  
  75.   
  76.     /** 
  77.      * 删除多个 
  78.      * <br>------------------------------<br> 
  79.      * @param keys 
  80.      */  
  81.     public void delete(List<String> keys) {  
  82.         redisTemplate.delete(keys);  
  83.     }  
  84.   
  85.     /** 
  86.      * 修改  
  87.      * <br>------------------------------<br> 
  88.      * @param user 
  89.      * @return  
  90.      */  
  91.     public boolean update(final User user) {  
  92.         String key = user.getId();  
  93.         if (get(key) == null) {  
  94.             throw new NullPointerException("数据行不存在, key = " + key);  
  95.         }  
  96.         boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
  97.             public Boolean doInRedis(RedisConnection connection)  
  98.                     throws DataAccessException {  
  99.                 RedisSerializer<String> serializer = getRedisSerializer();  
  100.                 byte[] key  = serializer.serialize(user.getId());  
  101.                 byte[] name = serializer.serialize(user.getName());  
  102.                 connection.set(key, name);  
  103.                 return true;  
  104.             }  
  105.         });  
  106.         return result;  
  107.     }  
  108.   
  109.     /**  
  110.      * 通过key获取 
  111.      * <br>------------------------------<br> 
  112.      * @param keyId 
  113.      * @return 
  114.      */  
  115.     public User get(final String keyId) {  
  116.         User result = redisTemplate.execute(new RedisCallback<User>() {  
  117.             public User doInRedis(RedisConnection connection)  
  118.                     throws DataAccessException {  
  119.                 RedisSerializer<String> serializer = getRedisSerializer();  
  120.                 byte[] key = serializer.serialize(keyId);  
  121.                 byte[] value = connection.get(key);  
  122.                 if (value == null) {  
  123.                     return null;  
  124.                 }  
  125.                 String name = serializer.deserialize(value);  
  126.                 return new User(keyId, name, null);  
  127.             }  
  128.         });  
  129.         return result;  
  130.     }  
  131. }  

8、测试类RedisTest

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.lyz.test;  
  2. import java.util.ArrayList;  
  3. import java.util.List;  
  4.   
  5. import junit.framework.Assert;  
  6.   
  7. import org.junit.Test;  
  8. import org.springframework.beans.factory.annotation.Autowired;  
  9. import org.springframework.test.context.ContextConfiguration;  
  10. import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;  
  11.   
  12. import com.lyz.dao.IUserDao;  
  13. import com.lyz.entity.User;  
  14.   
  15.   
  16. /** 
  17.  * Redis测试类 
  18.  * @author liuyazhuang 
  19.  * 
  20.  */  
  21. @ContextConfiguration(locations = {"classpath*:applicationContext.xml"})  
  22. public class RedisTest extends AbstractJUnit4SpringContextTests {  
  23.       
  24.     @Autowired  
  25.     private IUserDao userDao;  
  26.       
  27.     /** 
  28.      * 新增 
  29.      * <br>------------------------------<br> 
  30.      */  
  31.     @Test  
  32.     public void testAddUser() {  
  33.         User user = new User();  
  34.         user.setId("user1");  
  35.         user.setName("liuyazhuang");  
  36.         boolean result = userDao.add(user);  
  37.         Assert.assertTrue(result);  
  38.     }  
  39.       
  40.     /** 
  41.      * 批量新增 普通方式 
  42.      * <br>------------------------------<br> 
  43.      */  
  44.     @Test  
  45.     public void testAddUsers1() {  
  46.         List<User> list = new ArrayList<User>();  
  47.         for (int i = 10; i < 50000; i++) {  
  48.             User user = new User();  
  49.             user.setId("user" + i);  
  50.             user.setName("liuyazhuang" + i);  
  51.             list.add(user);  
  52.         }  
  53.         long begin = System.currentTimeMillis();  
  54.         for (User user : list) {  
  55.             userDao.add(user);  
  56.         }  
  57.         System.out.println(System.currentTimeMillis() -  begin);  
  58.     }  
  59.       
  60.     /** 
  61.      * 批量新增 pipeline方式 
  62.      * <br>------------------------------<br> 
  63.      */  
  64.     @Test  
  65.     public void testAddUsers2() {  
  66.         List<User> list = new ArrayList<User>();  
  67.         for (int i = 10; i < 1500000; i++) {  
  68.             User user = new User();  
  69.             user.setId("user" + i);  
  70.             user.setName("liuyazhuang" + i);  
  71.             list.add(user);  
  72.         }  
  73.         long begin = System.currentTimeMillis();  
  74.         boolean result = userDao.add(list);  
  75.         System.out.println(System.currentTimeMillis() - begin);  
  76.         Assert.assertTrue(result);  
  77.     }  
  78.       
  79.     /** 
  80.      * 修改 
  81.      * <br>------------------------------<br> 
  82.      */  
  83.     @Test  
  84.     public void testUpdate() {  
  85.         User user = new User();  
  86.         user.setId("user1");  
  87.         user.setName("liuyazhuang");  
  88.         boolean result = userDao.update(user);  
  89.         Assert.assertTrue(result);  
  90.     }  
  91.       
  92.     /** 
  93.      * 通过key删除单个 
  94.      * <br>------------------------------<br> 
  95.      */  
  96.     @Test  
  97.     public void testDelete() {  
  98.         String key = "user1";  
  99.         userDao.delete(key);  
  100.     }  
  101.       
  102.     /** 
  103.      * 批量删除 
  104.      * <br>------------------------------<br> 
  105.      */  
  106.     @Test  
  107.     public void testDeletes() {  
  108.         List<String> list = new ArrayList<String>();  
  109.         for (int i = 0; i < 10; i++) {  
  110.             list.add("user" + i);  
  111.         }  
  112.         userDao.delete(list);  
  113.     }  
  114.       
  115.     /** 
  116.      * 获取 
  117.      * <br>------------------------------<br> 
  118.      */  
  119.     @Test  
  120.     public void testGetUser() {  
  121.         String id = "user1";  
  122.         User user = userDao.get(id);  
  123.         Assert.assertNotNull(user);  
  124.         Assert.assertEquals(user.getName(), "liuyazhuang");  
  125.     }  
  126.   
  127.     /** 
  128.      * 设置userDao 
  129.      * @param userDao the userDao to set 
  130.      */  
  131.     public void setUserDao(IUserDao userDao) {  
  132.         this.userDao = userDao;  
  133.     }  
  134. }  
0 0
原创粉丝点击