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

redis实现spring-redis-data的入门实例的更多相关文章

  1. Spring中IoC的入门实例

    Spring中IoC的入门实例 Spring的模块化是很强的,各个功能模块都是独立的,我们可以选择的使用.这一章先从Spring的IoC开始.所谓IoC就是一个用XML来定义生成对象的模式,我们看看如 ...

  2. 峰Redis学习(2)Jedis 入门实例

    参考博客:http://blog.java1234.com/blog/articles/314.html 第一节:使用Jedis 连接Redis 新建maven项目: pom.xml: <pro ...

  3. spring boot + jpa + kotlin入门实例

    spring boot +jpa的文章网络上已经有不少,这里主要补充一下用kotlin来做. kotlin里面的data class来创建entity可以帮助我们减少不少的代码,比如现在这个User的 ...

  4. Redis与Spring Data Redis

    1.Redis概述 1.1介绍 官网:https://redis.io/ Redis是一个开源的使用ANSIC语言编写.支持网络.可基于内存 亦可持久化的日志型.Key-Value型的高性能数据库. ...

  5. 【主流技术】Redis 在 Spring 框架中的实践

    前言 在Java Spring 项目中,数据与远程数据库的频繁交互对服务器的内存消耗比较大,而 Redis 的特性可以有效解决这样的问题. Redis 的几个特性: Redis 以内存作为数据存储介质 ...

  6. 【redis】基于redis实现分布式并发锁

    基于redis实现分布式并发锁(注解实现) 说明 前提, 应用服务是分布式或多服务, 而这些"多"有共同的"redis"; (2017-12-04) 笑哭, 写 ...

  7. 把Spring Cloud Data Flow部署在Kubernetes上,再跑个任务试试

    1 前言 欢迎访问南瓜慢说 www.pkslow.com获取更多精彩文章! Spring Cloud Data Flow在本地跑得好好的,为什么要部署在Kubernetes上呢?主要是因为Kubern ...

  8. spring redis入门

    小二,上菜!!! 1. 虚拟机上安装redis服务 下载tar包,wget http://download.redis.io/releases/redis-2.8.19.tar.gz. 解压缩,tar ...

  9. Spring Boot 2.x 缓存应用 Redis注解与非注解方式入门教程

    Redis 在 Spring Boot 2.x 中相比 1.5.x 版本,有一些改变.redis 默认链接池,1.5.x 使用了 jedis,而2.x 使用了 lettuce Redis 接入 Spr ...

  10. Redis整合Spring结合使用缓存实例

    林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文介绍了如何在Spring中配置redis,并通过Spring中AOP的思想,将缓存的 ...

随机推荐

  1. SQL Server中Delete语句表名不能用别名

    delete from TABLEA A where A.FIELD1=10        (ORACLE适用)delete TABLEA from TABLEA A where A.FIELD1=1 ...

  2. .woff 文件404,配置到web.config

    <staticContent>        <remove fileExtension=".woff" />        <mimeMap fil ...

  3. poj3216

    这是一道描述非常不清楚的题目 首先解释一下,题目中的ti是任务开始时间不是结束时间, 然后维修人员可以理解为可以再任意时间从公司出发: 好,首先不难想到用floyd预处理一下: 然后我们把每个任务看成 ...

  4. SCADA软件整体架构

    SCADA软件整体框架如下所示: 1.免费版本可以支持的IO容量为2048点,无运行时间限制. 2.免费版本仅支持本地Runtime运行,CLServer服务器只能运行24小时. 3.免费版本支持的驱 ...

  5. window.location.search作用

    window.location.search.substr(1).split("&") 这里面的相关属性和时间还有参数能具体说明一下吗?window.location wi ...

  6. java基础之数据类型转换

    在写java程序时,经常会遇到需要数据类型转换,下面我们来介绍一些一些基本数据类型之间的转换. 1.int,folat,double,boolean,long 转换成字符串,其实很简单只需使用一个函数 ...

  7. 在MFC框架中使用OpenGL的简单实例

    引言 我们知道,在MFC框架中,用于绘图的接口是GDI.但GDI只能绘制简单的2D图形,要想制作精美的3D图形,一个可行的办法是使用OpenGL或者Direct3D等第三方库. 由于最近在给导师的一个 ...

  8. vs2013 报错AccessViolationException 解决方案

    最近 用vs2013 vs2010开发一个web 项目的时候  报AccessViolationException 异常 ,找不到原因 后边网上看了解决方法,试了一下 解决了,具体什么原因搞不清. 下 ...

  9. 2016"百度之星" - 初赛(Astar Round2B) 1006 中位数计数

    思路:统计当前数左边比它小|大 i个人,相应右边就应该是比它大|小i个人 l数组表示左边i个人的方案 r表示右边i个人的方案 数组下标不可能是负数所以要加n //#pragma comment(lin ...

  10. 大数据架构师基础:hadoop家族,Cloudera产品系列等各种技术

    大数据我们都知道hadoop,可是还会各种各样的技术进入我们的视野:Spark,Storm,impala,让我们都反映不过来.为了能够更好的架构大数据项目,这里整理一下,供技术人员,项目经理,架构师选 ...