介绍

Jedis 是 Redis 官方推荐的 Java 连接开发工具,提供了比较全面的 Redis 命令的支持。Jedis 中的方法调用是比较底层的暴露的 Redis 的 API,也即 Jedis 中的 Java 方法基本和 Redis 的 API 保持着一致,了解 Redis 的 API,也就能熟练的使用 Jedis。
  Jedis 使用阻塞的 I/O,且其方法调用都是同步的,程序流需要等到 sockets 处理完 I/O 才能执行,不支持异步。Jedis 客户端实例不是线程安全的,所以需要通过连接池来使用 Jedis。

今日内容

  • 通过读取配置文件的方式连接redis-cli
  • 实现Jedis添加数据 (zset类型)
  • 实现Jedis查询一天范围的数据

开始

引入的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><properties><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target><spring-boot.version>2.1.6.RELEASE</spring-boot.version><fastjson.version>1.2.78</fastjson.version><jedis.version>2.7.0</jedis.version><mybatis.version>2.1.4</mybatis.version></properties><dependencies><!--        解决@ConfigurationProperties()提示的问题--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId></dependency><!--        SpringBoot依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--        mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--        jedis依赖--><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>${jedis.version}</version></dependency><!--        lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!-- json --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>${fastjson.version}</version></dependency><!--        mybatis--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>${mybatis.version}</version></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement></project>

代码我就挑主要的介绍了

配置

yml配置

myredis:redis:host: 127.0.0.1port: 6379password:#客户端连接超时时间timeout: 10000#最小空闲数:低于minIdle时,将创建新的连接minIdle: 50#最大空闲数:空闲连接数大于maxIdle时,将进行回收maxIdle: 300#最大连接数据库连接数,设 0 为没有限制maxTotal: 5000#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制maxWaitMillis: 1000#重连次数retryNum: 5

配置类

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;@ConfigurationProperties("myredis.redis")
@Data
@Configuration
public class RedisConfig {private String host;private Integer port;private String password;private Integer maxIdle;private Integer timeout;private Integer minIdle;private Integer maxTotal;private Integer maxWaitMillis;private Integer retryNum;
}

jedis工具类

package com.guyong.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;@Configuration
public class JedisUtils {private Logger logger=Logger.getLogger(this.getClass().getName());@Autowiredprivate RedisConfig config;private Map<String,JedisPool> maps = new HashMap<>();private JedisPool pool;/*** 获取jedis连接对象* @return*/public  JedisPool getPool(){String key=config.getHost()+":"+config.getPort();//containsKey(key)判断是否包含指定键名if (!maps.containsKey(key)){JedisPoolConfig poolConfig = new JedisPoolConfig();poolConfig.setMaxIdle(config.getMaxIdle());poolConfig.setTestOnBorrow(true);poolConfig.setTestOnCreate(true);pool = new JedisPool(poolConfig, config.getHost(), config.getPort(), config.getMaxIdle());maps.put(key,pool);}else{pool=maps.get(key);}return pool;}/*** 连接jedis* @return*/public Jedis getJedis(){Jedis jedis = null;int count = 0;do{try{count++;//getResource()获取资源jedis=getPool().getResource();}catch(Exception e){e.printStackTrace();
//                关闭连接池getPool().close();
//                关闭jedisjedis.close();}}while(jedis == null && count<config.getRetryNum());return jedis;}/*** 断开jedis* @param jedis*/public void closeJedis(Jedis jedis){if (null != jedis){jedis.close();
//            pool.close();}}/*** 获取前24小时时间范围的值* @param key* @param jedis* @return*/public Set<String> getZset(String key,Jedis jedis){//minusHours() 要减去的小时时间//起始时间为当前时间24小时前LocalDateTime sparseTimeStart = LocalDateTime.now().minusHours(24);//结束时间为当前时间LocalDateTime sparseTimeEnd = LocalDateTime.now();//toInstant(ZoneOffset.of("+8")) 先将localDateTime转换成0时区时间,而ZoneOffset表示偏移量,在这里表示localDateTime比0时区偏移了+8个小时//计算出时间戳.toEpochMilli()Set<String> strings = jedis.zrangeByScore(key, sparseTimeStart.toInstant(ZoneOffset.of("+8")).toEpochMilli(), sparseTimeEnd.toInstant(ZoneOffset.of("+8")).toEpochMilli());return strings;}}

service

接口

import java.util.List;public interface RedisService {/***获取rediszset类型排序后的数据* @param paramTypeId* @return*/List<DeviceParamLogVo> redisFindLog(Long paramTypeId);/*** 添加zset类型的数据* @param param*/void AddData(String param);}

实现类

package com.guyong.service.impl;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guyong.config.JedisUtils;
import com.guyong.constant.DataTypeConstant;
import com.guyong.dao.DeviceParamTypeDao;
import com.guyong.entity.DeviceParamType;
import com.guyong.service.DeviceParamTypeService;
import com.guyong.service.RedisService;
import com.guyong.vo.DeviceParamLogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;@Service
public class RedisServiceImpl implements RedisService {@Autowiredprivate JedisUtils utils;@Autowiredprivate DeviceParamTypeService deviceParamTypeService;@Overridepublic List<DeviceParamLogVo> redisFindLog(Long paramTypeId) {Jedis jedis = utils.getJedis();try{DeviceParamType deviceParamType = deviceParamTypeService.findById(paramTypeId);String name = deviceParamType.getName();Integer dataType = deviceParamType.getDataType();String key = getCurrentDate();Set<String> zset = utils.getZset(key, jedis);List<DeviceParamLogVo> list = new ArrayList<>();zset.forEach((String s) -> {DeviceParamLogVo vo = new DeviceParamLogVo();//获取zset的score值Double zscore = jedis.zscore(key, s);long timestamp = zscore.longValue();String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");LocalDateTime parse = LocalDateTime.parse(format, df);//上传时间vo.setUpLoadTime(parse);JSONObject json = JSON.parseObject(s);String properties = json.get("properties").toString();JSONObject aJson = JSON.parseObject(properties);Object value;if (!properties.contains(deviceParamType.getName())) {value = "0";} else {value = deviceParamTypeService.getValue(aJson.get(name), dataType);}if (DataTypeConstant.LONG.equals(dataType)) {vo.setCurrentValueLong(Long.parseLong(value.toString()));} else if (DataTypeConstant.DECIMAL.equals(dataType)) {vo.setCurrentValueDecimal(new BigDecimal(value.toString()));}//属性名称vo.setAttributeName(deviceParamType.getTitle());//当前值vo.setCurrentValueString(String.valueOf(value));list.add(vo);});return list;}finally {utils.closeJedis(jedis);}}@Overridepublic void AddData(String param) {//获取jedis连接Jedis jedis = utils.getJedis();//Double.parseDouble(System.currentTimeMillis() + "") 获取当前时间戳jedis.zadd(getCurrentDate(), Double.parseDouble(System.currentTimeMillis() + ""), param);}private static String getCurrentDate(){//获取当前时间转成年月日格式Date date = new Date();SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");String day = simpleDateFormat.format(date);String key =day+"";return key;}
}

redisFindLog类的实现代码可以跟着实际的业务进行更改

结尾

zset的key值存储的是当前时间戳,value就是需要的取值
其实取前一天的时间范围就是根据时间戳范围进行取值

SpringBoot使用Jedis实现zset数据类型获取过去24h的数据相关推荐

  1. SpringBoot整合freemarker中自定义标签获取字典表的数据

    因为在前端要根据字典表中的数据去将1.2这些值转换成对应的文字解释 1.首先要创建一个类去实现 TemplateDirectiveModel 类 @Component public class Dic ...

  2. zset中的score_每天五分钟,成就redis大神之Zset数据类型

    Zset类型有序集合和集合一样也是string类型元素的集合,且不允许重复的成员.不同的是每个元素都会关联一个double类型的分数.redis正是通过分数来为集合中的成员进行从小到大的排序.有序集合 ...

  3. SpringBoot 使用jedis整合redis实现缓存处理

    目录 简介 redis基本结构: 代码实现 1.新建Springboot项目,添加必要的依赖 pom.xml: 2. 在application.yml配置文件中添加 redis的相关配置 3.Spri ...

  4. springboot使用jedis

    springboot使用jedis 1 lettuce 和 jedis 对比 2 jedis的使用 2.1 redis key增加统一前缀 2.2 redis value配置序列化方法 2.3 red ...

  5. SpringBoot整合Jedis

    我们在使用springboot搭建微服务的时候,在很多时候还是需要redis的高速缓存来缓存一些数据,存储一些高频率访问的数据,如果直接使用redis的话又比较麻烦,在这里,我们使用jedis来实现r ...

  6. SpringBoot之获取配置文件中的数据

    SpringBoot之获取配置文件中的数据 项目结构 配置application.properties book.author=Tom book.name=SpringBoot # spring.pr ...

  7. redis中Zset数据类型最全常用命令

    一.引言 今天晚上不加班,不加班,爽翻.不加班就能安安心心继续学习了,继续redis学习哈.今天学习redis五大数据类型最后一个了.上一章学习了Set无序集合,那么有无序集合肯定就会有有序集合了.Z ...

  8. 【二十四】springboot使用EasyExcel和线程池实现多线程导入Excel数据

      springboot篇章整体栏目:  [一]springboot整合swagger(超详细 [二]springboot整合swagger(自定义)(超详细) [三]springboot整合toke ...

  9. Springboot+poi+实现导出导入Excle表格+Vue引入echarts数据展示

    需求: 一. 数据库数据表导出Excle表格 二. Excle数据导入数据库 三. Vue引入Echarts数据展示 工具: idea 数据库: mysql 框架:Springboot 准备工作: 1 ...

最新文章

  1. [Web 开发] 定制IE下载对话框的按钮(打开/保存)
  2. Pytorch使用CPU运行“Torch not compiled with CUDA enabled”
  3. python 学堂在线_最新网课答案2020学堂在线Python 交互式程序设计导论
  4. 详细设计 存储分配_【存储论文笔记】Windows Azure Storage
  5. 2-OAuth2腾讯微博开放平台API小试
  6. 关于AOSP与AOKP
  7. CE-RTI开源软件代码学习笔记(一)
  8. 自定义配置文件 /etc/httpd/conf.d
  9. arch linux yaourt arm,在ARM設備(樹莓派、香蕉派)上為Arch Linux配置yaourt
  10. matlab二元多项式求值,matlab多项式代入求值
  11. VS2019下添加include和lib
  12. ATF lds和代码section如何关联
  13. deform服务器位置,Deform V11 自动多工步分析(MO)设置详解-工艺成型及仿真
  14. 如何进行性能测试的调优
  15. linux下批量改文件名命令,Linux 批量更改文件名命令
  16. iOS 所需英语词汇整理
  17. Python 模块介绍
  18. AndroidStudio报错:Failed to start monitoring CJL0217113005096
  19. 【计算机网络知识扫盲】02、计算机网络的概念(转)
  20. 阿里巴巴干儿子奥哲完成数亿元C轮融资,用低代码让数字化触手可及

热门文章

  1. 美式英语与英式英语的区别
  2. 织梦dedecms怎么安装?如何本地环境搭建网站?
  3. Tik Tok跨境卖家最常见的问题详细解答
  4. 12306火车余票查询API
  5. 新构造运动名词解释_新构造运动与新构造
  6. unity之StartCoroutine运行机制--懵逼了
  7. 思岚科技机器人自主定位导航方案:高效可靠、高精度、厘米级别地图多场景适用 | 百万人学AI评选
  8. 日语を、が、は用法全解
  9. SEO实战干货:利用高权重网站借力操作关键词快速排名!
  10. linux的xmgrace无法运行,xmgrace (转)