经理提出新的需求,需要知道每天微信推送了多少条模板消息,成功多少条,失败多少条,想到用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. JAVA软件工程师应该具备的技能有哪些?

    前言:有朋友问我:学历和能力哪个重要?我个人觉得能力大于学历,没有能力哪来的学历,学历只是证明能力的一方面.为此在能力方面畅谈java软件工程师必备的能力.作为一名合格的java工程师,不仅需要学历, ...

  2. C# for 遍历 IPagedList

    IPagedList<Doc> ss = Doclist.ToPagedList(page, pageSize); ;i<ss.Count;i++) { var yy = ss[i] ...

  3. Commons IO

    Common IO 是一个工具库,用来帮助开发IO功能 它包括6个主要部分 Utility classes – 包括一些静态方法来执行常用任务 Input – InputStream 和 Reader ...

  4. Git server出现cache大回收分析

    实例 git server是一个io密集型的服务,当cache量很大的时候,cache会全部一次释放,导致那么一瞬间,IO read压力很大,因为,用户的大量请求,需要重新从磁盘读到内存,但是这个时刻 ...

  5. 关于js开发中保留小数位计算函数(以向上取整或向下取整的方式保留小数)

    前端工作中经常遇到数字计算保留小数问题,由于不是四舍五入的方式不能使用toFixed函数,本文采用正则表达式匹配字符串的方式,解决对数字的向上或向下保留小数问题: 1.向上保留小数(只要目标小数位后有 ...

  6. PY简易爬虫

    然而,实用性很差,仅仅是能用而已. 已知bug: 由于土啬的问题,经常会炸掉.网络不稳定导致各种Connection Aborted/SSLError: EOF occurred in violati ...

  7. mysql5.7忘记root密码

    systemctl stop mysqld.service vi /etc/my.cnf [mysqld] skip-grant-tables skip-networking mysql -uroot ...

  8. fzu 2087并查集的运用求最小生成树的等效边

    //对数组排序后,对于边相同并且边的两端不在一个集合内的一定是等效边或者必加边, //第一数数,第二合并集合 #include<stdio.h> #include<stdlib.h& ...

  9. 使用 Redis及其产品定位

    实际MySQL是适合进行海量数据存储的,通过Memcached将热点数据加载到cache,加速访问,很多公司都曾经使用过这样的架构,但随着业务数据量的不断增加,和访问量的持续增长,我们遇到了很多问题: ...

  10. COGS——C610. 数对的个数

    http://cogs.pro/cogs/problem/problem.php?pid=610 Description出题是一件痛苦的事情!题目看多了也有审美疲劳,于是我舍弃了大家所熟悉的A+B P ...