经理提出新的需求,需要知道每天微信推送了多少条模板消息,成功多少条,失败多少条,想到用Redis缓存,网上查了一些资料,Redis中有方法increment,测试代码如下

  

Controller

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; /**
* @author wangqq
* @version 创建时间:2018年8月10日 下午2:30:47
* 类说明
*/
@Controller
@RequestMapping("test")
public class TestController { @Resource
private TestService testService; @RequestMapping("testRedis")
@ResponseBody
public int testRedis (){
return testService.testRedis ();
}
}

Service

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service; /**
* @author wangqq
* @version 创建时间:2018年8月10日 下午2:32:13
* 类说明
*/
@Service
public class TestService { @Resource
RedisTemplate<String,Object> redisTemplate; @Resource(name="redisTemplate")
private ValueOperations<String,Object> ops; public int testRedis() {
try {
//此方法会先检查key是否存在,存在+1,不存在先初始化,再+1
ops.increment("success", 1); return (int) ops.get("success");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} return 0 ;
} }

直接使用ops.get("success"),会出现错误,报错信息 Caused by: org.springframework.core.serializer.support.SerializationFailedException: Failed to deserialize payload. Is the byte array a result of corresponding serialization for DefaultDeserializer?; nested exception is java.io.EOFException。 根据信息,可以看到是反序列化出错,上网查一下,貌似是因为JDK序列化之后,反序列化失败。解决办法:

第一种解决办法

用 redisTemplate.boundValueOps("success").get(0, -1)获得key值

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service; /**
* @author wangqq
* @version 创建时间:2018年8月10日 下午2:32:13
* 类说明
*/
@Service
public class TestService { @Resource
RedisTemplate<String,Object> redisTemplate; @Resource(name="redisTemplate")
private ValueOperations<String,Object> ops; public int testRedis() {
try {
//此方法会先检查key是否存在,存在+1,不存在先初始化,再+1
ops.increment("success", 1); //return (int) ops.get("success"); return Integer.valueOf(redisTemplate.boundValueOps("success").get(0, -1));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} return 0 ;
} }

页面显示为2,因为第一次已经成功了,只是get失败了

第二种解决办法

添加一个方法 getKey

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service; /**
* @author wangqq
* @version 创建时间:2018年8月10日 下午2:32:13
* 类说明
*/
@Service
public class TestService { @Resource
RedisTemplate<String,Object> redisTemplate; @Resource(name="redisTemplate")
private ValueOperations<String,Object> ops; public int testRedis() {
try {
//此方法会先检查key是否存在,存在+1,不存在先初始化,再+1
ops.increment("success", 1); //return (int) ops.get("success"); //return Integer.valueOf(redisTemplate.boundValueOps("success").get(0, -1)); return (int) getKey("success");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} return 0 ;
} public long getKey(final String key) { return redisTemplate.execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> redisSerializer = redisTemplate.getStringSerializer(); byte[] rowkey = redisSerializer.serialize(key);
byte[] rowval = connection.get(rowkey); try {
String val = redisSerializer.deserialize(rowval);
return Long.parseLong(val);
} catch (Exception e) {
return 0L;
}
}
});
} }

页面返回

最后一步,设置每天零点过期,重新计数

//当天时间
Date date = new Date();
//当天零点
date = DateUtils.truncate(date, Calendar.DAY_OF_MONTH);
//第二天零点
date = DateUtils.addDays(date, +1); redisTemplate.expireAt("success", date);

redis实现计数--------Redis increment的更多相关文章

  1. 华为云PB级数据库GaussDB(for Redis)揭秘第八期:用高斯 Redis 进行计数

    摘要:高斯Redis,计数的最佳选择! 一.背景 当我们打开手机刷微博时,就要开始和各种各样的计数器打交道了.我们注册一个帐号后,微博就会给我们记录一组数据:关注数.粉丝数.动态数-:我们刷帖时,关注 ...

  2. Redis作者谈Redis应用场景(转)

    add by zhj : 这是Redis的作者antirez在他的技术博客中写的一篇文章 英文原文:take-advantage-of-redis-adding-it-to-your-stack 译文 ...

  3. 高可用Redis(七):Redis持久化

    1.什么是持久化 持久化就是将数据从掉电易失的内存同步到能够永久存储的设备上的过程 2.Redis为什么需要持久化 redis将数据保存在内存中,一旦Redis服务器被关闭,或者运行Redis服务的主 ...

  4. Redis 基础:Redis 数据类型

    Redis 数据类型 Redis支持五种数据类型:string(字符串).hash(哈希).list(列表).set(集合)及zset(sorted set:有序集合). String(字符串) st ...

  5. Redis之配置文件redis.conf

    解读下 redis.conf 配置文件中常用的配置项,为不显得过于臃长,已选择性删除原配置文件中部分注释. # Redis must be started with the file path as ...

  6. Redis(3) 配置文件 redis.conf

    Redis.conf 配置详解: # Redis configuration file example. # # Note that in order to read the configuratio ...

  7. 分布式数据存储 之 Redis(一) —— 初识Redis

    分布式数据存储 之 Redis(一) -- 初识Redis 为什么要学习并运用Redis?Redis有什么好处?我们步入Redis的海洋,初识Redis. 一.Redis是什么 ​ Redis 是一个 ...

  8. redis基础及redis特殊场景使用描述

    数据类型 String set list hash zset redis原理 单线程:redis是单线程+io多路复用:检查文件描述的就绪状态 对比memchached:多线程+锁 redis优势 解 ...

  9. Redis 实战 —— 14. Redis 的 Lua 脚本编程

    简介 Redis 从 2.6 版本开始引入使用 Lua 编程语言进行的服务器端脚本编程功能,这个功能可以让用户直接在 Redis 内部执行各种操作,从而达到简化代码并提高性能的作用. P248 在不编 ...

随机推荐

  1. sql server like 在将值转换成数据类型int失败

    select * from table where title like '%'?'%'; 采用? 传参会报错:sql server like 在将值转换成数据类型int失败 select * fro ...

  2. C#调用FFMPEG实现桌面录制(视频+音频+生成本地文件)

    不得不说FFMPEG真是个神奇的玩意,所接触的部分不过万一.网上有个很火的例子是c++方面的,当然这个功能还是用c++来实现比较妥当. 然而我不会c++ 因为我的功能需求比较简单,只要实现基本的录制就 ...

  3. 解决:惠普HP LaserJet Pro M126a MFP 驱动 安装失败,及其它同类打印机失败问题

    注意:如果在 Windows XP 系统下安装出错,请先安装WindowsXP KB971276-v3补丁后再安装装驱动. 下载地址:http://www.dyjqd.com/soft/KB97127 ...

  4. hibernate中的懒加载和急加载

    懒加载(FatchType.LAZY)是Hibernate为提高程序执行效率而提供的一种机制,简单说就是只有正真使用其属性的时候,数据库才会进行查询. 具体的执行过程就是:Hibernate从数据库获 ...

  5. sessionStorage和localStorage存储的转换不了json

    先说说localStorage与sessionStorage的差别 sessionStorage是存储浏览器的暂时性的数据,当关闭浏览器下次再打开的时候就不能拿到之前存储的缓存了 localStora ...

  6. PAT_A1125#Chain the Ropes

    Source: PAT A1125 Chain the Ropes (25 分) Description: Given some segments of rope, you are supposed ...

  7. Mysql [Err] 1118 - Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535.

    对于越来越多的数据,数据库的容量越来越大,压缩也就越来越常见了.在我的实际工作中进行过多次压缩工作,也遇到多次问题,在此和大家分享一下. 首先,我们先说说怎么使用innodb的压缩. 第一,mysql ...

  8. Lua的五种变量类型、局部变量、全局变量、lua运算符、流程控制if语句_学习笔记02

    Lua的五种变量类型.局部变量.全局变量 .lua运算符 .流程控制if语句 Lua代码的注释方式: --当行注释 --[[    多行注释    ]]-- Lua的5种变量类型: 1.null 表示 ...

  9. [系统资源攻略]IO第一篇-磁盘IO,内核IO概念

    几个基本的概念 在研究磁盘性能之前我们必须先了解磁盘的结构,以及工作原理.不过在这里就不再重复说明了,关系硬盘结构和工作原理的信息可以参考维基百科上面的相关词条--Hard disk drive(英文 ...

  10. [转载]ext4文件系统的delalloc选项造成单次写延迟增加的分析

    转载http://www.cnblogs.com/cobbliu/p/5603472.html 最近我们的服务进程遇到kill -15后处于Z的状态,变为了僵尸进程,经过/proc/{thread_i ...