redis实现spring-redis-data的入门实例

发布时间:2020-07-11编辑:脚本学堂
本文分享下,redis中实现spring-redis-data的方法与例子,有需要的朋友可以参考学习下。

redis的客户端实现、主要分为spring-redis-data 、jredis。

记录下spring-redis-data的学习心得;
spring-redis-data 中我目前主要用了它的存、取、清除。

redis配置redis-manager-config.properties :
 

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

spring 中配置
 

<bean id="propertyConfigurerRedis" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="order" value="1" />
        <property name="ignoreUnresolvablePlaceholders" value="true" />
        <property name="locations">
            <list>
                <value>classpath:config/redis-manager-config.properties</value>
            </list>
        </property>
    </bean>

        <!-- jedis pool配置 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxActive" value="${redis.maxActive}" />
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxWait" value="${redis.maxWait}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>

    <!-- spring data redis -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="usePool" value="true"></property>
        <property name="hostName" value="${redis.host}" />
        <property name="port" value="${redis.port}" />
        <property name="password" value="${redis.pass}" />
        <property name="timeout" value="${redis.timeout}" />
        <property name="database" value="${redis.default.db}"></property>
        <constructor-arg index="0" ref="jedisPoolConfig" />
    </bean>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
    </bean>
<!--配置一个基础类(之后的业务类继承于该类)、将redisTemplate注入 -->
<bean id="redisBase" abstract="true">
  <property name="template" ref="redisTemplate"></property>
 </bean>

java代码:
 

复制代码 代码示例:

public class RedisBase {
    private StringRedisTemplate template;

    /**
     * @return the template
     */
    public StringRedisTemplate getTemplate() {
        return template;
    }

    /**
     * @param template the template to set
     */
    public void setTemplate(StringRedisTemplate template) {
        this.template = template;
    }

}
 

继续:
具体redis的值的写入、读出、清除缓存!
第一:写入
 

复制代码 代码示例:

public class StudentCountDO {
      private Long id;
         private String studentId;
          private Long commentHeadCount;
         private Long docAttitudeScores;
         private Long guideServiceScores;
          private Long treatEffectCount;
         private Long treatEffectScores;
      private String gmtModified;
      private String gmtCreated;
          private Long waitingTimeScores;
     }

StringRedisTemplate template = getTemplate();//获得上面注入的template
       // save as hash 一般key都要加一个前缀,方便清除所有的这类key
       BoundHashOperations<String, String, String> ops = template.boundHashOps("student:"+studentCount.getStudentId());

       Map<String, String> data = new HashMap<String, String>();
       data.put("studentId", CommentUtils.convertNull(studentCount.getStudentId()));
       data.put("commentHeadCount", CommentUtils.convertLongToString(studentCount.getCommentHeadCount()));
       data.put("docAttitudeScores", CommentUtils.convertLongToString(studentCount.getDocAttitudeScores()));
       data.put("guideServicesScores", CommentUtils.convertLongToString(studentCount.getGuideServiceScores()));
       data.put("treatEffectCount", CommentUtils.convertLongToString(studentCount.getTreatEffectCount()));
       data.put("treatEffectScores", CommentUtils.convertLongToString(studentCount.getTreatEffectScores()));
       data.put("waitingTimeScores", CommentUtils.convertLongToString(studentCount.getWaitingTimeScores()));
       try {
           ops.putAll(data);
       } catch (Exception e) {
           logger.error(CommentConstants.WRITE_EXPERT_COMMENT_COUNT_REDIS_ERROR + studentCount.studentCount(), e);
       }
 

第二、 取出
 

复制代码 代码示例:
public StudentCountDO getStudentCommentCountInfo(String studentId) {
       final String strkey = "student:"+ studentId;
       return getTemplate().execute(new RedisCallback<StudentCountDO>() {
           @Override
           public StudentCountDO doInRedis(RedisConnection connection) throws DataAccessException {
               byte[] bkey = getTemplate().getStringSerializer().serialize(strkey);
               if (connection.exists(bkey)) {
                   List<byte[]> value = connection.hMGet(bkey,
                           getTemplate().getStringSerializer().serialize("studentId"), getTemplate()
                                   .getStringSerializer().serialize("commentHeadCount"), getTemplate()
                                   .getStringSerializer().serialize("docAttitudeScores"), getTemplate()
                                   .getStringSerializer().serialize("guideServicesScores"), getTemplate()
                                   .getStringSerializer().serialize("treatEffectCount"), getTemplate()
                                   .getStringSerializer().serialize("treatEffectScores"), getTemplate()
                                   .getStringSerializer().serialize("waitingTimeScores"));
                   StudentCountDO studentCommentCountDO = new StudentCountDO();
                   studentCommentCountDO.setExpertId(getTemplate().getStringSerializer().deserialize(value.get(0)));
                   studentCommentCountDO.setCommentHeadCount(Long.parseLong(getTemplate().getStringSerializer()
                           .deserialize(value.get(1))));
                   studentCommentCountDO.setDocAttitudeScores(Long.parseLong(getTemplate().getStringSerializer()
                           .deserialize(value.get(2))));
                   studentCommentCountDO.setGuideServiceScores(Long.parseLong(getTemplate().getStringSerializer()
                           .deserialize(value.get(3))));
                   studentCommentCountDO.setTreatEffectCount(Long.parseLong(getTemplate().getStringSerializer()
                           .deserialize(value.get(4))));
                   studentCommentCountDO.setTreatEffectScores(Long.parseLong(getTemplate().getStringSerializer()
                           .deserialize(value.get(5))));
                   studentCommentCountDO.setWaitingTimeScores(Long.parseLong(getTemplate().getStringSerializer()
                           .deserialize(value.get(6))));
                   return studentCommentCountDO;
               }
               return null;
           }
       });
}

这个存和取的过程其实是把对象中的各个字段序列化之后存入到hashmap 、取出来的时候在进行按照存入进去的顺序进行取出。
第三 清除
这个就根据前面的前缀很简单了,一句代码就搞定啦!
 

复制代码 代码示例:
private void clear(String pattern) {
       StringRedisTemplate template = getTemplate();
       Set<String> keys = template.keys(pattern);
       if (!keys.isEmpty()) {
           template.delete(keys);
       }
}

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