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

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

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

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

[html] view plaincopy

  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 plaincopy

  1. redis.maxWait=1000//最大建立连接等待时间  

  2. redis.testOnBorrow=true//<span style=“font-size:12px;”>指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个</span>  

spring 中配置

[html] view plaincopy

  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 plaincopy

  1.    

[html] view plaincopy

  1. <!–配置一个基础类(之后的业务类继承于该类)、将redisTemplate注入 –>  

[html] view plaincopy

  1. <bean id=“redisBase” abstract=“true”>  

  2.   <property name=“template” ref=“redisTemplate”></property>  

  3.  </bean>  

java代码:

[java] view plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  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: 就可以将该类型的所有缓存清除掉喽!

 

 

 

 

版权声明:本文为博主原创文章,未经博主允许不得转载。