经理提出新的需求,需要知道每天微信推送了多少条模板消息,成功多少条,失败多少条,想到用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. 4 Things I Wish I Would Have Known When I Started My Software Development Career【当我最开始从事软件工程师的时候我希望我知道的四件事】

    英文原文:http://simpleprogrammer.com/2013/08/19/software-development-career/ My software development car ...

  2. Hive2.1.1集群搭建

    软件环境: linux系统: CentOS6.7 Hadoop版本: 2.6.5 zookeeper版本: 3.4.8 主机配置: 一共m1, m2, m3这五部机, 每部主机的用户名都为centos ...

  3. html5 web worker学习笔记(记一)

    (吐槽:浏览器js终于进入多线程时代!) 以前利用setTimeout.setInterval等方式的多线程,是伪多线程,本质上是一种在单线程中进行队列执行的方式.自从html5 web worker ...

  4. ★Java语法(四)——————————运算符

    使用除法“/”  ,要特别注意数据类型的问题.若被除数和除数都是整形,且被除数不能被除数整除时,这时输出的结果为整数,(即整形数/整形数=整形数),这是因为整形变量无法保存小数点后面的数据所致,要特别 ...

  5. Haar、pico、npd、dlib等多种人脸检测特征及算法结果比较

    原文:opencv.pico.npd.dlib.face++等多种人脸检测算法结果比较 NDP检测结果: 结果分析: Pico(Pixel Intensity Comparison-based Obj ...

  6. 安卓代码迁移:ActionBarActivity: cannot be resolved to a type

    参考链接:http://stackoverflow.com/questions/18830736/actionbaractivity-cannot-be-resolved-to-a-type in e ...

  7. MQTTnet 的Asp.Net Core 认证事件的扩展

    MQTTnet 的数据接收 连接 等事件都很丰富, 唯独客户端连接验证不能依赖注入也不能很舒服的使用事件的方式, 因此MQTTnet.AspNetCoreEx 就出现了. 示例如下:在  public ...

  8. 【转载】intellij idea如何将web项目打成war包

    1.点击[File]->[Project Structure]菜单(或使用Shift+Ctrl+Alt+S快捷键),打开[Project Structure]窗口.如下图: 2.在[Projec ...

  9. 【Shell编程】Shell基本语法

    Shell 语法   Shell程序设计作为一种脚本语言,在Linux系统中有广泛的应用,本文记录了关于Shell程序设计的基础语法知识和常用命令,方便查询,熟练使用shell也需要经常实践,这对于完 ...

  10. Linux direct io使用例子

    Linux direct io使用 在linux 2.6内核上使用direct io不难,只需按照如下几点来做即可: 1,在open文件时加上O_DIRECT旗标,这样以通告内核我们想对该文件进行直接 ...