介绍
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.1
port: 6379
password:
#客户端连接超时时间
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());
@Autowired
private 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();
// 关闭jedis
jedis.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 {
@Autowired
private JedisUtils utils;
@Autowired
private DeviceParamTypeService deviceParamTypeService;
@Override
public 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);
}
}
@Override
public 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就是需要的取值
其实取前一天的时间范围就是根据时间戳范围进行取值