zoukankan      html  css  js  c++  java
  • Spring 整合 Redis(转)

    转自http://blog.csdn.net/java2000_wl/article/details/8543203

    pom构建:

    1. <modelVersion>4.0.0</modelVersion>  
    2. <groupId>com.x.redis</groupId>  
    3. <artifactId>springredis</artifactId>  
    4. <version>0.0.1-SNAPSHOT</version>  
    5.   
    6. <dependencies>  
    7.     <dependency>  
    8.         <groupId>org.springframework.data</groupId>  
    9.         <artifactId>spring-data-redis</artifactId>  
    10.         <version>1.0.2.RELEASE</version>  
    11.     </dependency>  
    12.     <dependency>  
    13.         <groupId>org.springframework</groupId>  
    14.         <artifactId>spring-test</artifactId>  
    15.         <version>3.1.2.RELEASE</version>  
    16.         <scope>test</scope>  
    17.     </dependency>  
    18.       
    19.     <dependency>  
    20.         <groupId>redis.clients</groupId>  
    21.         <artifactId>jedis</artifactId>  
    22.         <version>2.1.0</version>  
    23.     </dependency>  
    24.       
    25.      <dependency>  
    26.         <groupId>junit</groupId>  
    27.         <artifactId>junit</artifactId>  
    28.         <version>4.8.2</version>  
    29.         <scope>test</scope>  
    30.     </dependency>  
    31. </dependencies>  


    spring配置文件(applicationContext.xml):

    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.x.dao.impl.UserDao" />   
    28. </beans>  

    redis.properties

    1. # Redis settings  
    2. redis.host=localhost  
    3. redis.port=6379  
    4. redis.pass=java2000_wl  
    5.   
    6.   
    7. redis.maxIdle=300  
    8. redis.maxActive=600  
    9. redis.maxWait=1000  
    10. redis.testOnBorrow=true  

    java代码:

    1. package com.x.entity;  
    2.   
    3. import java.io.Serializable;  
    4.   
    5. /**  
    6.  * @author http://blog.csdn.net/java2000_wl  
    7.  * @version <b>1.0</b>  
    8.  */   
    9. public class User implements Serializable {  
    10.       
    11.     private static final long serialVersionUID = -6011241820070393952L;  
    12.   
    13.     private String id;  
    14.       
    15.     private String name;  
    16.       
    17.     private String password;  
    18.   
    19.     /** 
    20.      * <br>------------------------------<br> 
    21.      */  
    22.     public User() {  
    23.           
    24.     }  
    25.       
    26.     /** 
    27.      * <br>------------------------------<br> 
    28.      */  
    29.     public User(String id, String name, String password) {  
    30.         super();  
    31.         this.id = id;  
    32.         this.name = name;  
    33.         this.password = password;  
    34.     }  
    35.   
    36.     /** 
    37.      * 获得id 
    38.      * @return the id 
    39.      */  
    40.     public String getId() {  
    41.         return id;  
    42.     }  
    43.   
    44.     /** 
    45.      * 设置id 
    46.      * @param id the id to set 
    47.      */  
    48.     public void setId(String id) {  
    49.         this.id = id;  
    50.     }  
    51.   
    52.     /** 
    53.      * 获得name 
    54.      * @return the name 
    55.      */  
    56.     public String getName() {  
    57.         return name;  
    58.     }  
    59.   
    60.     /** 
    61.      * 设置name 
    62.      * @param name the name to set 
    63.      */  
    64.     public void setName(String name) {  
    65.         this.name = name;  
    66.     }  
    67.   
    68.     /** 
    69.      * 获得password 
    70.      * @return the password 
    71.      */  
    72.     public String getPassword() {  
    73.         return password;  
    74.     }  
    75.   
    76.     /** 
    77.      * 设置password 
    78.      * @param password the password to set 
    79.      */  
    80.     public void setPassword(String password) {  
    81.         this.password = password;  
    82.     }  
    83. }  
    1. package com.x.dao;  
    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.  * AbstractBaseRedisDao 
    9.  * @author http://blog.csdn.net/java2000_wl  
    10.  * @version <b>1.0</b>  
    11.  */   
    12. public abstract class AbstractBaseRedisDao<K, V> {  
    13.       
    14.     @Autowired  
    15.     protected RedisTemplate<K, V> redisTemplate;  
    16.   
    17.     /** 
    18.      * 设置redisTemplate 
    19.      * @param redisTemplate the redisTemplate to set 
    20.      */  
    21.     public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {  
    22.         this.redisTemplate = redisTemplate;  
    23.     }  
    24.       
    25.     /** 
    26.      * 获取 RedisSerializer 
    27.      * <br>------------------------------<br> 
    28.      */  
    29.     protected RedisSerializer<String> getRedisSerializer() {  
    30.         return redisTemplate.getStringSerializer();  
    31.     }  
    32. }  
    1. package com.x.dao;  
    2.   
    3. import java.util.List;  
    4.   
    5. import com.x.entity.User;  
    6.   
    7. /**  
    8.  * @author http://blog.csdn.net/java2000_wl  
    9.  * @version <b>1.0</b>  
    10.  */   
    11. public interface IUserDao {  
    12.       
    13.     /** 
    14.      * 新增 
    15.      * <br>------------------------------<br> 
    16.      * @param user 
    17.      * @return 
    18.      */  
    19.     boolean add(User user);  
    20.       
    21.     /** 
    22.      * 批量新增 使用pipeline方式 
    23.      * <br>------------------------------<br> 
    24.      * @param list 
    25.      * @return 
    26.      */  
    27.     boolean add(List<User> list);  
    28.       
    29.     /** 
    30.      * 删除 
    31.      * <br>------------------------------<br> 
    32.      * @param key 
    33.      */  
    34.     void delete(String key);  
    35.       
    36.     /** 
    37.      * 删除多个 
    38.      * <br>------------------------------<br> 
    39.      * @param keys 
    40.      */  
    41.     void delete(List<String> keys);  
    42.       
    43.     /** 
    44.      * 修改 
    45.      * <br>------------------------------<br> 
    46.      * @param user 
    47.      * @return  
    48.      */  
    49.     boolean update(User user);  
    50.   
    51.     /** 
    52.      * 通过key获取 
    53.      * <br>------------------------------<br> 
    54.      * @param keyId 
    55.      * @return  
    56.      */  
    57.     User get(String keyId);  
    58. }  
    1. package com.x.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.x.dao.AbstractBaseRedisDao;  
    13. import com.x.dao.IUserDao;  
    14. import com.x.entity.User;  
    15.   
    16. /**  
    17.  * Dao 
    18.  * @author http://blog.csdn.net/java2000_wl  
    19.  * @version <b>1.0</b>  
    20.  */   
    21. public class UserDao 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.         }, false, true);  
    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. }  
      1. import java.util.ArrayList;  
      2. import java.util.List;  
      3.   
      4. import junit.framework.Assert;  
      5.   
      6. import org.junit.Test;  
      7. import org.springframework.beans.factory.annotation.Autowired;  
      8. import org.springframework.test.context.ContextConfiguration;  
      9. import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;  
      10.   
      11. import com.x.dao.IUserDao;  
      12. import com.x.entity.User;  
      13.   
      14. /**  
      15.  * 测试 
      16.  * @author http://blog.csdn.net/java2000_wl  
      17.  * @version <b>1.0</b>  
      18.  */    
      19. @ContextConfiguration(locations = {"classpath*:applicationContext.xml"})  
      20. public class RedisTest extends AbstractJUnit4SpringContextTests {  
      21.       
      22.     @Autowired  
      23.     private IUserDao userDao;  
      24.       
      25.     /** 
      26.      * 新增 
      27.      * <br>------------------------------<br> 
      28.      */  
      29.     @Test  
      30.     public void testAddUser() {  
      31.         User user = new User();  
      32.         user.setId("user1");  
      33.         user.setName("java2000_wl");  
      34.         boolean result = userDao.add(user);  
      35.         Assert.assertTrue(result);  
      36.     }  
      37.       
      38.     /** 
      39.      * 批量新增 普通方式 
      40.      * <br>------------------------------<br> 
      41.      */  
      42.     @Test  
      43.     public void testAddUsers1() {  
      44.         List<User> list = new ArrayList<User>();  
      45.         for (int i = 10; i < 50000; i++) {  
      46.             User user = new User();  
      47.             user.setId("user" + i);  
      48.             user.setName("java2000_wl" + i);  
      49.             list.add(user);  
      50.         }  
      51.         long begin = System.currentTimeMillis();  
      52.         for (User user : list) {  
      53.             userDao.add(user);  
      54.         }  
      55.         System.out.println(System.currentTimeMillis() -  begin);  
      56.     }  
      57.       
      58.     /** 
      59.      * 批量新增 pipeline方式 
      60.      * <br>------------------------------<br> 
      61.      */  
      62.     @Test  
      63.     public void testAddUsers2() {  
      64.         List<User> list = new ArrayList<User>();  
      65.         for (int i = 10; i < 1500000; i++) {  
      66.             User user = new User();  
      67.             user.setId("user" + i);  
      68.             user.setName("java2000_wl" + i);  
      69.             list.add(user);  
      70.         }  
      71.         long begin = System.currentTimeMillis();  
      72.         boolean result = userDao.add(list);  
      73.         System.out.println(System.currentTimeMillis() - begin);  
      74.         Assert.assertTrue(result);  
      75.     }  
      76.       
      77.     /** 
      78.      * 修改 
      79.      * <br>------------------------------<br> 
      80.      */  
      81.     @Test  
      82.     public void testUpdate() {  
      83.         User user = new User();  
      84.         user.setId("user1");  
      85.         user.setName("new_password");  
      86.         boolean result = userDao.update(user);  
      87.         Assert.assertTrue(result);  
      88.     }  
      89.       
      90.     /** 
      91.      * 通过key删除单个 
      92.      * <br>------------------------------<br> 
      93.      */  
      94.     @Test  
      95.     public void testDelete() {  
      96.         String key = "user1";  
      97.         userDao.delete(key);  
      98.     }  
      99.       
      100.     /** 
      101.      * 批量删除 
      102.      * <br>------------------------------<br> 
      103.      */  
      104.     @Test  
      105.     public void testDeletes() {  
      106.         List<String> list = new ArrayList<String>();  
      107.         for (int i = 0; i < 10; i++) {  
      108.             list.add("user" + i);  
      109.         }  
      110.         userDao.delete(list);  
      111.     }  
      112.       
      113.     /** 
      114.      * 获取 
      115.      * <br>------------------------------<br> 
      116.      */  
      117.     @Test  
      118.     public void testGetUser() {  
      119.         String id = "user1";  
      120.         User user = userDao.get(id);  
      121.         Assert.assertNotNull(user);  
      122.         Assert.assertEquals(user.getName(), "java2000_wl");  
      123.     }  
      124.   
      125.     /** 
      126.      * 设置userDao 
      127.      * @param userDao the userDao to set 
      128.      */  
      129.     public void setUserDao(IUserDao userDao) {  
      130.         this.userDao = userDao;  
      131.     }  
      132. }  
  • 相关阅读:
    【Leetcode_easy】922. Sort Array By Parity II
    【Leetcode_easy】925. Long Pressed Name
    【Leetcode_easy】872. Leaf-Similar Trees
    【Leetcode_easy】874. Walking Robot Simulation
    【Leetcode_easy】1128. Number of Equivalent Domino Pairs
    【VxWorks工程】基于opencv创建读取摄像头数据的工程error
    【Leetcode_easy】868. Binary Gap
    【Leetcode_easy】867. Transpose Matrix
    【Leetcode_easy】860. Lemonade Change
    第11章 拾遗5:IPv6和IPv4共存技术(3)_NAT-PT技术【全书完】
  • 原文地址:https://www.cnblogs.com/-lpf/p/4274091.html
Copyright © 2011-2022 走看看