redis实现 spring-redis-data初学习

今天看了一些redis的客户端实现、主要分为spring-redis-data 、jredis

今天先记录下spring-redis-data的学习心得;

spring-redis-data 中我目前主要用了它的存、取、清除。

先看配置吧redis-manager-config.properties :

[html]  view plain copy
  1. redis.host=192.168.1.20//redis的服务器地址  
  2. redis.port=6400//redis的服务端口  
  3. redis.pass=1234xxxxx//密码  
  4. redis.default.db=0//链接数据库  
  5. redis.timeout=100000//客户端超时时间单位是毫秒  
  6. redis.maxActive=300// 最大连接数  
  7. redis.maxIdle=100//最大空闲数  
[html]  view plain copy
  1. redis.maxWait=1000//最大建立连接等待时间  
  2. redis.testOnBorrow=true//<span style="font-size:12px;">指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个</span>  

spring 中配置

[html]  view plain copy
  1. <bean id="propertyConfigurerRedis" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  2.         <property name="order" value="1" />  
  3.         <property name="ignoreUnresolvablePlaceholders" value="true" />  
  4.         <property name="locations">  
  5.             <list>  
  6.                 <value>classpath:config/redis-manager-config.properties</value>  
  7.             </list>  
  8.         </property>  
  9.     </bean>  
  10.       
  11.         <!-- jedis pool配置 -->  
  12.     <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
  13.         <property name="maxActive" value="${redis.maxActive}" />  
  14.         <property name="maxIdle" value="${redis.maxIdle}" />  
  15.         <property name="maxWait" value="${redis.maxWait}" />  
  16.         <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
  17.     </bean>  
  18.   
  19.     <!-- spring data redis -->  
  20.     <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
  21.         <property name="usePool" value="true"></property>  
  22.         <property name="hostName" value="${redis.host}" />  
  23.         <property name="port" value="${redis.port}" />  
  24.         <property name="password" value="${redis.pass}" />  
  25.         <property name="timeout" value="${redis.timeout}" />  
  26.         <property name="database" value="${redis.default.db}"></property>  
  27.         <constructor-arg index="0" ref="jedisPoolConfig" />  
  28.     </bean>  
  29.       
  30.     <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
  31.         <property name="connectionFactory" ref="jedisConnectionFactory" />  
  32.     </bean>  
[html]  view plain copy
  1.    
[html]  view plain copy
  1. <!--配置一个基础类(之后的业务类继承于该类)、将redisTemplate注入 -->  
[html]  view plain copy
  1. <bean id="redisBase" abstract="true">  
  2.   <property name="template" ref="redisTemplate"></property>  
  3.  </bean>  


java代码:

[java]  view plain copy
  1. public class RedisBase {  
  2.   
  3.     private StringRedisTemplate template;  
  4.   
  5.     /** 
  6.      * @return the template 
  7.      */  
  8.     public StringRedisTemplate getTemplate() {  
  9.         return template;  
  10.     }  
  11.   
  12.     /** 
  13.      * @param template the template to set 
  14.      */  
  15.     public void setTemplate(StringRedisTemplate template) {  
  16.         this.template = template;  
  17.     }  
  18.   
  19. }  

继续:

下面就是具体redis的值的写入、读出、清除缓存喽!

第一:写入

[java]  view plain copy
  1. public class StudentCountDO {  
  2.   
  3.     private Long id;  
  4.   
  5.        private String studentId;  
  6.   
  7.         private Long commentHeadCount;  
  8.   
  9.        private Long docAttitudeScores;  
  10.   
  11.        private Long guideServiceScores;  
  12.   
  13.         private Long treatEffectCount;  
  14.   
  15.        private Long treatEffectScores;  
  16.   
  17.     private String gmtModified;  
  18.   
  19.     private String gmtCreated;  
  20.   
  21.         private Long waitingTimeScores;  
  22.   
  23.    }  


 

[java]  view plain copy
  1. StringRedisTemplate template = getTemplate();//获得上面注入的template  
  2.        // save as hash 一般key都要加一个前缀,方便清除所有的这类key  
  3.        BoundHashOperations<String, String, String> ops = template.boundHashOps("student:"+studentCount.getStudentId());  
  4.   
  5.        Map<String, String> data = new HashMap<String, String>();  
  6.        data.put("studentId", CommentUtils.convertNull(studentCount.getStudentId()));  
  7.        data.put("commentHeadCount", CommentUtils.convertLongToString(studentCount.getCommentHeadCount()));  
  8.        data.put("docAttitudeScores", CommentUtils.convertLongToString(studentCount.getDocAttitudeScores()));  
  9.        data.put("guideServicesScores", CommentUtils.convertLongToString(studentCount.getGuideServiceScores()));  
  10.        data.put("treatEffectCount", CommentUtils.convertLongToString(studentCount.getTreatEffectCount()));  
  11.        data.put("treatEffectScores", CommentUtils.convertLongToString(studentCount.getTreatEffectScores()));  
  12.        data.put("waitingTimeScores", CommentUtils.convertLongToString(studentCount.getWaitingTimeScores()));  
  13.        try {  
  14.            ops.putAll(data);  
  15.        } catch (Exception e) {  
  16.            logger.error(CommentConstants.WRITE_EXPERT_COMMENT_COUNT_REDIS_ERROR + studentCount.studentCount(), e);  
  17.        }  

第二、 取出

[java]  view plain copy
  1. public StudentCountDO getStudentCommentCountInfo(String studentId) {  
  2.        final String strkey = "student:"+ studentId;  
  3.        return getTemplate().execute(new RedisCallback<StudentCountDO>() {  
  4.            @Override  
  5.            public StudentCountDO doInRedis(RedisConnection connection) throws DataAccessException {  
  6.                byte[] bkey = getTemplate().getStringSerializer().serialize(strkey);  
  7.                if (connection.exists(bkey)) {  
  8.                    List<byte[]> value = connection.hMGet(bkey,  
  9.                            getTemplate().getStringSerializer().serialize("studentId"), getTemplate()  
  10.                                    .getStringSerializer().serialize("commentHeadCount"), getTemplate()  
  11.                                    .getStringSerializer().serialize("docAttitudeScores"), getTemplate()  
  12.                                    .getStringSerializer().serialize("guideServicesScores"), getTemplate()  
  13.                                    .getStringSerializer().serialize("treatEffectCount"), getTemplate()  
  14.                                    .getStringSerializer().serialize("treatEffectScores"), getTemplate()  
  15.                                    .getStringSerializer().serialize("waitingTimeScores"));  
  16.                    StudentCountDO studentCommentCountDO = new StudentCountDO();  
  17.                    studentCommentCountDO.setExpertId(getTemplate().getStringSerializer().deserialize(value.get(0)));  
  18.                    studentCommentCountDO.setCommentHeadCount(Long.parseLong(getTemplate().getStringSerializer()  
  19.                            .deserialize(value.get(1))));  
  20.                    studentCommentCountDO.setDocAttitudeScores(Long.parseLong(getTemplate().getStringSerializer()  
  21.                            .deserialize(value.get(2))));  
  22.                    studentCommentCountDO.setGuideServiceScores(Long.parseLong(getTemplate().getStringSerializer()  
  23.                            .deserialize(value.get(3))));  
  24.                    studentCommentCountDO.setTreatEffectCount(Long.parseLong(getTemplate().getStringSerializer()  
  25.                            .deserialize(value.get(4))));  
  26.                    studentCommentCountDO.setTreatEffectScores(Long.parseLong(getTemplate().getStringSerializer()  
  27.                            .deserialize(value.get(5))));  
  28.                    studentCommentCountDO.setWaitingTimeScores(Long.parseLong(getTemplate().getStringSerializer()  
  29.                            .deserialize(value.get(6))));  
  30.                    return studentCommentCountDO;  
  31.                }  
  32.                return null;  
  33.            }  
  34.        });  
  35.    }  

这个存和取的过程其实是把对象中的各个字段序列化之后存入到hashmap 、取出来的时候在进行按照存入进去的顺序进行取出。

第三 清除

这个就根据前面的前缀很简单了,一句代码就搞定啦!

[java]  view plain copy
  1. private void clear(String pattern) {  
  2.        StringRedisTemplate template = getTemplate();  
  3.        Set<String> keys = template.keys(pattern);  
  4.        if (!keys.isEmpty()) {  
  5.            template.delete(keys);  
  6.        }  
  7.    }  

pattern传入为student: 就可以将该类型的所有缓存清除掉喽!


  1. 1, Redis Hello World 的例子  
  2.   
  3. 这里用的包是Jedis。下载地址https://github.com/xetorthio/jedis/downloads  
  4.   
  5. 把jar包引入工程,打开redis的服务器(redis下载及安装见初步理解Redis及其安装配置)。开始打招呼的例子,如下  
  6.   
  7.    1:  Jedis jedis = new Jedis("localhost");  
  8.   
  9.    2:  jedis.set("key""Hello World!");  
  10.   
  11.    3:  String value = jedis.get("key");  
  12.   
  13.    4:  System.out.println(value);  
  14.   
  15. 分别测试下各种数据结构  
  16.   
  17.         System.out.println("==String==");  
  18.   
  19.         Jedis jedis = new Jedis("localhost");  
  20.   
  21.         //String   
  22.   
  23.         jedis.set("key""Hello World!");  
  24.   
  25.         String value = jedis.get("key");  
  26.   
  27.         System.out.println(value);  
  28.   
  29.           
  30.   
  31.         //List   
  32.   
  33.         System.out.println("==List==");  
  34.   
  35.         jedis.rpush("messages""Hello how are you?");  
  36.   
  37.         jedis.rpush("messages""Fine thanks. I'm having fun with redis.");  
  38.   
  39.         jedis.rpush("messages""I should look into this NOSQL thing ASAP");  
  40.   
  41.         List<String> values = jedis.lrange("messages"0, -1);  
  42.   
  43.         System.out.println(values);  
  44.   
  45.           
  46.   
  47.         //Set   
  48.   
  49.         System.out.println("==Set==");  
  50.   
  51.         jedis.sadd("myset""1");  
  52.   
  53.         jedis.sadd("myset""2");  
  54.   
  55.         jedis.sadd("myset""3");  
  56.   
  57.         jedis.sadd("myset""4");  
  58.   
  59.         Set<String> setValues = jedis.smembers("myset");  
  60.   
  61.         System.out.println(setValues);  
  62.   
  63.           
  64.   
  65.         //Sorted Set   
  66.   
  67.         jedis.zadd("hackers"1940"Alan Kay");  
  68.   
  69.         jedis.zadd("hackers"1953"Richard Stallman");  
  70.   
  71.         jedis.zadd("hackers"1965"Yukihiro Matsumoto");  
  72.   
  73.         jedis.zadd("hackers"1916"Claude Shannon");  
  74.   
  75.         jedis.zadd("hackers"1969"Linus Torvalds");  
  76.   
  77.         jedis.zadd("hackers"1912"Alan Turing");  
  78.   
  79.         setValues = jedis.zrange("hackers"0, -1);  
  80.   
  81.         System.out.println(setValues);  
  82.   
  83.           
  84.   
  85.         //Hash   
  86.   
  87.         System.out.println("==Hash==");  
  88.   
  89.         Map<String, String> pairs = new HashMap<String, String>();  
  90.   
  91.         pairs.put("name""Akshi");  
  92.   
  93.         pairs.put("age""2");  
  94.   
  95.         pairs.put("sex""Female");  
  96.   
  97.         jedis.hmset("kid", pairs);  
  98.   
  99.         values = jedis.hmget("kid"new String[]{"name""age""sex"});  
  100.   
  101.         System.out.println(values);  
  102.   
  103.           
  104.   
  105.         setValues = jedis.hkeys("kid");  
  106.   
  107.         System.out.println(setValues);  
  108.   
  109.         values = jedis.hvals("kid");  
  110.   
  111.         System.out.println(values);  
  112.   
  113.         pairs = jedis.hgetAll("kid");  
  114.   
  115.         System.out.println(pairs);  
  116.   
  117. 然后解决持久化的问题  
  118.   
  119. redis是把所有的数据都放在内存的一种机制,需要经常同步到磁盘保证数据的持久化。数据全放在内存里,真的很担心我的小机器啊~回头数据大了调台式机上把,再大了就。。。  
  120.   
  121. 这个题目比较大些,以后可以单独写几篇,现在急着用,入门么,解决问题先。主要是两种机制,快照(Snapshotting)和AOF(Append-only file)。AOF每次写操作都会写日志,服务器当机的时候从那些日志文件里恢复。不过日志文件会特别大,我的机器肯定承受不起。快照是默认的方式,默认是每小时更新一次,手动调用save, shutdown, slave这些命令也会写日志。测试下save。  
  122.   
  123. 先用客户端查询一下刚才代码插入的东西。  
  124.   
  125. image  
  126.   
  127. 东西还是在内存里的。然后把服务器关了。重新开启,还是有结果。  
  128.   
  129. image  
  130.   
  131. 验证是不是因为时间过太久了自动保存了,用java代码新插入一个值。继续关服务器和重启等操作。  
  132.   
  133. image  
  134.   
  135. 没有值。证明之前的值存在确实是因为自动保存了,接着重新插入(这个如果覆盖是个什么情况呢:貌似直接无情地覆盖了),然后执行下保存。之后关闭,重启。  
  136.   
  137. jedis.set("newkey""Hello New New World!");  
  138. String value = jedis.get("newkey");  
  139. System.out.println(value);  
  140. jedis.save();  
  141.   
  142. image  
  143.   
  144. 可以看到newkey的值了,而且是覆盖后的。save执行后会进行一次日志备份。够用了,先到这里吧。  
  145. 转载于http://blog.youkuaiyun.com/samtribiani/article/details/7609322

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值