经理提出新的需求,需要知道每天微信推送了多少条模板消息,成功多少条,失败多少条,想到用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. akka框架——异步非阻塞高并发处理框架

    akka actor, akka cluster akka是一系列框架,包括akka-actor, akka-remote, akka-cluster, akka-stream等,分别具有高并发处理模 ...

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

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

  3. 转:Fiddler抓包工具总结

    http://www.cnblogs.com/yyhh/p/5140852.html#l02

  4. EMC VNX5200/5400存储 新增LUN与Hosts映射操作

    EMC VNX5200/5400 1.创建RAID  Groups 1.1        进入EMC VNX5200/5400主界面,依次选择Storage——Storage Pools——RAID ...

  5. idea中git回滚到指定分支

    1.git - > show history,选中回滚的指定版本,右击copy revision number 粘出版本号 2.git -> reset hard 出险新页面之后,选中ha ...

  6. [置顶] tcpflow 抓包

    转自:  http://www.rwifeng.com/jekyll/update/2015/04/16/how-to-tcpflow/ tcpflow 抓包 Apr 16, 2015 大家都知道 t ...

  7. case...when...then if 用法

    select case when if 的一些用法 概述:sql语句中的case语句与高级语言中的switch语句,是标准sql的语法,适用于一个条件判断有多种值的情况下分别执行不同的操作. 首先,让 ...

  8. 使用Selenium爬取网站表格类数据

    本文转载自一下网站:Python爬虫(5):Selenium 爬取东方财富网股票财务报表 https://www.makcyun.top/web_scraping_withpython5.html 需 ...

  9. svg文件报错

    错误:The content of element type "font-face" is incomplete, it must match "((font-face- ...

  10. Linux学习笔记之1——文件和目录管理(硬连接和软连接)(连结档,相当于快捷方式)

    在这节将要学习linux的连接档,在之前用"ls -l" 查看文件属性的命令时, 其中第二个属性是连接数.那么这个连接数是干什么的?这就要理解inode. 先说一下文件是怎么存储的 ...