设为首页 收藏本站
查看: 1104|回复: 0

[经验分享] Spring 整合Redis详解(增删改查、PipleLine、测试代码)

[复制链接]

尚未签到

发表于 2016-12-20 11:11:59 | 显示全部楼层 |阅读模式
pom构建:
 
[html] view plaincopyprint? 



  • <modelVersion>4.0.0</modelVersion>  
  • <groupId>com.x.redis</groupId>  
  • <artifactId>springredis</artifactId>  
  • <version>0.0.1-SNAPSHOT</version>  
  •   
  • <dependencies>  
  •     <dependency>  
  •         <groupId>org.springframework.data</groupId>  
  •         <artifactId>spring-data-redis</artifactId>  
  •         <version>1.0.2.RELEASE</version>  
  •     </dependency>  
  •     <dependency>  
  •         <groupId>org.springframework</groupId>  
  •         <artifactId>spring-test</artifactId>  
  •         <version>3.1.2.RELEASE</version>  
  •         <scope>test</scope>  
  •     </dependency>  
  •       
  •     <dependency>  
  •         <groupId>redis.clients</groupId>  
  •         <artifactId>jedis</artifactId>  
  •         <version>2.1.0</version>  
  •     </dependency>  
  •       
  •      <dependency>  
  •         <groupId>junit</groupId>  
  •         <artifactId>junit</artifactId>  
  •         <version>4.8.2</version>  
  •         <scope>test</scope>  
  •     </dependency>  
  • </dependencies>  

  
spring配置文件(applicationContext.xml):
 
[html] view plaincopyprint? 



  • <?xml version="1.0" encoding="UTF-8"?>  
  • <beans xmlns="http://www.springframework.org/schema/beans"  
  •     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  •     xmlns:context="http://www.springframework.org/schema/context"  
  •     xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"  
  •     xmlns:aop="http://www.springframework.org/schema/aop"  
  •     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.xsd">  
  •   
  •     <context:property-placeholder location="classpath:redis.properties" />  
  •   
  •     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
  •         <property name="maxIdle" value="${redis.maxIdle}" />  
  •         <property name="maxActive" value="${redis.maxActive}" />  
  •         <property name="maxWait" value="${redis.maxWait}" />  
  •         <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
  •     </bean>  
  •       
  •     <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
  •         p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"  p:pool-config-ref="poolConfig"/>  
  •       
  •     <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
  •         <property name="connectionFactory"   ref="connectionFactory" />  
  •     </bean>         
  •       
  •     <bean id="userDao" class="com.x.dao.impl.UserDao" />   
  • </beans>  

  redis.properties
 
 
[html] view plaincopyprint? 



  • # Redis settings  
  • redis.host=localhost  
  • redis.port=6379  
  • redis.pass=java2000_wl  
  •   
  •   
  • redis.maxIdle=300  
  • redis.maxActive=600  
  • redis.maxWait=1000  
  • redis.testOnBorrow=true  

 
java代码:
 
[java] view plaincopyprint? 



  • package com.x.entity;  
  •   
  • import java.io.Serializable;  
  •   
  • /**  
  •  * @author http://blog.csdn.net/java2000_wl  
  •  * @version <b>1.0</b>  
  •  */   
  • public class User implements Serializable {  
  •       
  •     private static final long serialVersionUID = -6011241820070393952L;  
  •   
  •     private String id;  
  •       
  •     private String name;  
  •       
  •     private String password;  
  •   
  •     /** 
  •      * <br>------------------------------<br> 
  •      */  
  •     public User() {  
  •           
  •     }  
  •       
  •     /** 
  •      * <br>------------------------------<br> 
  •      */  
  •     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;  
  •     }  
  • }  

[java] view plaincopyprint? 



  • 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 <b>1.0</b>  
  •  */   
  • public abstract class AbstractBaseRedisDao<K, V> {  
  •       
  •     @Autowired  
  •     protected RedisTemplate<K, V> redisTemplate;  
  •   
  •     /** 
  •      * 设置redisTemplate 
  •      * @param redisTemplate the redisTemplate to set 
  •      */  
  •     public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {  
  •         this.redisTemplate = redisTemplate;  
  •     }  
  •       
  •     /** 
  •      * 获取 RedisSerializer 
  •      * <br>------------------------------<br> 
  •      */  
  •     protected RedisSerializer<String> getRedisSerializer() {  
  •         return redisTemplate.getStringSerializer();  
  •     }  
  • }  

[java] view plaincopyprint? 



  • package com.x.dao;  
  •   
  • import java.util.List;  
  •   
  • import com.x.entity.User;  
  •   
  • /**  
  •  * @author http://blog.csdn.net/java2000_wl  
  •  * @version <b>1.0</b>  
  •  */   
  • public interface IUserDao {  
  •       
  •     /** 
  •      * 新增 
  •      * <br>------------------------------<br> 
  •      * @param user 
  •      * @return 
  •      */  
  •     boolean add(User user);  
  •       
  •     /** 
  •      * 批量新增 使用pipeline方式 
  •      * <br>------------------------------<br> 
  •      * @param list 
  •      * @return 
  •      */  
  •     boolean add(List<User> list);  
  •       
  •     /** 
  •      * 删除 
  •      * <br>------------------------------<br> 
  •      * @param key 
  •      */  
  •     void delete(String key);  
  •       
  •     /** 
  •      * 删除多个 
  •      * <br>------------------------------<br> 
  •      * @param keys 
  •      */  
  •     void delete(List<String> keys);  
  •       
  •     /** 
  •      * 修改 
  •      * <br>------------------------------<br> 
  •      * @param user 
  •      * @return  
  •      */  
  •     boolean update(User user);  
  •   
  •     /** 
  •      * 通过key获取 
  •      * <br>------------------------------<br> 
  •      * @param keyId 
  •      * @return  
  •      */  
  •     User get(String keyId);  
  • }  

[java] view plaincopyprint? 



  • 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 <b>1.0</b>  
  •  */   
  • public class UserDao extends AbstractBaseRedisDao<String, User> implements IUserDao {  
  •   
  •     /**  
  •      * 新增 
  •      *<br>------------------------------<br> 
  •      * @param user 
  •      * @return 
  •      */  
  •     public boolean add(final User user) {  
  •         boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
  •             public Boolean doInRedis(RedisConnection connection)  
  •                     throws DataAccessException {  
  •                 RedisSerializer<String> serializer = getRedisSerializer();  
  •                 byte[] key  = serializer.serialize(user.getId());  
  •                 byte[] name = serializer.serialize(user.getName());  
  •                 return connection.setNX(key, name);  
  •             }  
  •         });  
  •         return result;  
  •     }  
  •       
  •     /** 
  •      * 批量新增 使用pipeline方式   
  •      *<br>------------------------------<br> 
  •      *@param list 
  •      *@return 
  •      */  
  •     public boolean add(final List<User> list) {  
  •         Assert.notEmpty(list);  
  •         boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
  •             public Boolean doInRedis(RedisConnection connection)  
  •                     throws DataAccessException {  
  •                 RedisSerializer<String> serializer = getRedisSerializer();  
  •                 for (User user : list) {  
  •                     byte[] key  = serializer.serialize(user.getId());  
  •                     byte[] name = serializer.serialize(user.getName());  
  •                     connection.setNX(key, name);  
  •                 }  
  •                 return true;  
  •             }  
  •         }, falsetrue);  
  •         return result;  
  •     }  
  •       
  •     /**  
  •      * 删除 
  •      * <br>------------------------------<br> 
  •      * @param key 
  •      */  
  •     public void delete(String key) {  
  •         List<String> list = new ArrayList<String>();  
  •         list.add(key);  
  •         delete(list);  
  •     }  
  •   
  •     /** 
  •      * 删除多个 
  •      * <br>------------------------------<br> 
  •      * @param keys 
  •      */  
  •     public void delete(List<String> keys) {  
  •         redisTemplate.delete(keys);  
  •     }  
  •   
  •     /** 
  •      * 修改  
  •      * <br>------------------------------<br> 
  •      * @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<Boolean>() {  
  •             public Boolean doInRedis(RedisConnection connection)  
  •                     throws DataAccessException {  
  •                 RedisSerializer<String> serializer = getRedisSerializer();  
  •                 byte[] key  = serializer.serialize(user.getId());  
  •                 byte[] name = serializer.serialize(user.getName());  
  •                 connection.set(key, name);  
  •                 return true;  
  •             }  
  •         });  
  •         return result;  
  •     }  
  •   
  •     /**  
  •      * 通过key获取 
  •      * <br>------------------------------<br> 
  •      * @param keyId 
  •      * @return 
  •      */  
  •     public User get(final String keyId) {  
  •         User result = redisTemplate.execute(new RedisCallback<User>() {  
  •             public User doInRedis(RedisConnection connection)  
  •                     throws DataAccessException {  
  •                 RedisSerializer<String> 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 result;  
  •     }  
  • }  

[java] view plaincopyprint? 



  • import java.util.ArrayList;  
  • import java.util.List;  
  •   
  • import junit.framework.Assert;  
  •   
  • import org.junit.Test;  
  • import org.springframework.beans.factory.annotation.Autowired;  
  • import org.springframework.test.context.ContextConfiguration;  
  • import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;  
  •   
  • import com.x.dao.IUserDao;  
  • import com.x.entity.User;  
  •   
  • /**  
  •  * 测试 
  •  * @author http://blog.csdn.net/java2000_wl  
  •  * @version <b>1.0</b>  
  •  */    
  • @ContextConfiguration(locations = {"classpath*:applicationContext.xml"})  
  • public class RedisTest extends AbstractJUnit4SpringContextTests {  
  •       
  •     @Autowired  
  •     private IUserDao userDao;  
  •       
  •     /** 
  •      * 新增 
  •      * <br>------------------------------<br> 
  •      */  
  •     @Test  
  •     public void testAddUser() {  
  •         User user = new User();  
  •         user.setId("user1");  
  •         user.setName("java2000_wl");  
  •         boolean result = userDao.add(user);  
  •         Assert.assertTrue(result);  
  •     }  
  •       
  •     /** 
  •      * 批量新增 普通方式 
  •      * <br>------------------------------<br> 
  •      */  
  •     @Test  
  •     public void testAddUsers1() {  
  •         List<User> list = new ArrayList<User>();  
  •         for (int i = 10; i < 50000; i++) {  
  •             User user = new User();  
  •             user.setId("user" + i);  
  •             user.setName("java2000_wl" + i);  
  •             list.add(user);  
  •         }  
  •         long begin = System.currentTimeMillis();  
  •         for (User user : list) {  
  •             userDao.add(user);  
  •         }  
  •         System.out.println(System.currentTimeMillis() -  begin);  
  •     }  
  •       
  •     /** 
  •      * 批量新增 pipeline方式 
  •      * <br>------------------------------<br> 
  •      */  
  •     @Test  
  •     public void testAddUsers2() {  
  •         List<User> list = new ArrayList<User>();  
  •         for (int i = 10; i < 1500000; i++) {  
  •             User user = new User();  
  •             user.setId("user" + i);  
  •             user.setName("java2000_wl" + i);  
  •             list.add(user);  
  •         }  
  •         long begin = System.currentTimeMillis();  
  •         boolean result = userDao.add(list);  
  •         System.out.println(System.currentTimeMillis() - begin);  
  •         Assert.assertTrue(result);  
  •     }  
  •       
  •     /** 
  •      * 修改 
  •      * <br>------------------------------<br> 
  •      */  
  •     @Test  
  •     public void testUpdate() {  
  •         User user = new User();  
  •         user.setId("user1");  
  •         user.setName("new_password");  
  •         boolean result = userDao.update(user);  
  •         Assert.assertTrue(result);  
  •     }  
  •       
  •     /** 
  •      * 通过key删除单个 
  •      * <br>------------------------------<br> 
  •      */  
  •     @Test  
  •     public void testDelete() {  
  •         String key = "user1";  
  •         userDao.delete(key);  
  •     }  
  •       
  •     /** 
  •      * 批量删除 
  •      * <br>------------------------------<br> 
  •      */  
  •     @Test  
  •     public void testDeletes() {  
  •         List<String> list = new ArrayList<String>();  
  •         for (int i = 0; i < 10; i++) {  
  •             list.add("user" + i);  
  •         }  
  •         userDao.delete(list);  
  •     }  
  •       
  •     /** 
  •      * 获取 
  •      * <br>------------------------------<br> 
  •      */  
  •     @Test  
  •     public void testGetUser() {  
  •         String id = "user1";  
  •         User user = userDao.get(id);  
  •         Assert.assertNotNull(user);  
  •         Assert.assertEquals(user.getName(), "java2000_wl");  
  •     }  
  •   
  •     /** 
  •      * 设置userDao 
  •      * @param userDao the userDao to set 
  •      */  
  •     public void setUserDao(IUserDao userDao) {  
  •         this.userDao = userDao;  
  •     }  
  • }  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-316931-1-1.html 上篇帖子: memcached,mongdb,redis,Tokyo Tyrant的安装和使用 下篇帖子: Redis笔记(三)添加密码并修改默认端口后的主从同步
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表