Jedis的使用

Jedis的使用

文章目录

    • Jedis的使用
      • 1、引入依赖
      • 2、配置文件
      • 3、配置类
      • 4、工具类

1、引入依赖

        
        <dependency>
            <groupId>redis.clientsgroupId>
            <artifactId>jedisartifactId>
        dependency>

2、配置文件

spring:
  redis:
    # redis数据库索引(默认为0)
    database: 0
    # redis服务器地址(默认为localhost)
    host: 127.0.0.1
    # redis端口(默认为6379)
    port: 6379
    # redis访问密码(默认为空)
    password:
    # redis连接超时时间(单位毫秒)
    timeout: 5000
    # redis连接池配置
    lettuce:
      pool:
        # 最大可用连接数(默认为8,负数表示无限)
        max-active: 20
        # 最大空闲连接数(默认为8,负数表示无限)
        max-idle: 20
        # 最小空闲连接数(默认为0,该值只有为正数才有用)
        min-idle: 0
        # 从连接池中获取连接最大等待时间(默认为-1,单位为毫秒,负数表示无限)
        max-wait: -1

3、配置类

package com.hxlinks.system.config;

import com.hxlinks.common.exception.CustomException;
import com.hxlinks.common.util.JedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Jedis连接配置
 *
 * @author 微笑
 * @version 1.0
 * @date 2022/5/12 15:59
 */

@Configuration
@Slf4j
public class JedisConfig {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.lettuce.pool.max-active}")
    private int maxActive;
    @Value("${spring.redis.lettuce.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.lettuce.pool.min-idle}")
    private int minIdle;

    @Bean
    public JedisPool jedisPool() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setMaxTotal(maxActive);
        // 是否启用pool的jmx管理功能, 默认true
        jedisPoolConfig.setJmxEnabled(true);

        JedisPool jedisPool;
        if (StringUtils.isEmpty(password)) {
            jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
        } else {
            jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
        }
        JedisUtils.setJedisPool(jedisPool);
        try {
            Jedis jedis = JedisUtils.getJedis();
            if (jedis != null) {
                log.info("---[Jedis]---连接成功---;host = " + host + " ---port = " + port);
            } else {
                throw new CustomException("---[Jedis]---连接失败---;host = " + host + " ---port = " + port);
            }
            JedisUtils.close(jedis);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("---[Jedis]---连接失败---;host = " + host + " ---port = " + port);
        }
        return jedisPool;
    }

}

4、工具类

package com.hxlinks.common.util;

import com.alibaba.fastjson.JSON;
import com.hxlinks.common.dao.StationMapper;
import com.hxlinks.common.entity.RealTimeData;
import com.hxlinks.common.entity.Station;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Jedis工具类
 *
 * @author 微笑
 * @version 1.0
 * @date 2022/5/20 13:14
 */
@Slf4j
@Component
public class JedisUtils {

    /**
     * Jedis连接池实例
     */
    private static JedisPool jedisPool;

    /**
     * 设置Jedis连接池实例,从系统启动初始化时配置
     */
    public static void setJedisPool(JedisPool jedisPool) {
        JedisUtils.jedisPool = jedisPool;
    }

    /**
     * 获取Jedis资源
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    /**
     * 释放Jedis连接
     */
    public static void close(Jedis jedis) {
        try {
            if (jedis != null) {
                jedis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 服务对象
     */
    @Resource
    private StationMapper stationMapper;
    private static StationMapper stationDao;

    /**
     * 注释的方法,用于给静态属性赋值
     */
    @PostConstruct
    private void construct() {
        JedisUtils.stationDao = this.stationMapper;
    }

    //======================================String======================================

    /**
     * 单个KEY/VALUE 设置值
     */
    public static boolean set(String key, String value) {
        Jedis jedis = getJedis();
        if (jedis == null) {
            return false;
        }
        try {
            String result = jedis.set(key, value);
            if ("OK".equals(result)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            close(jedis);
        }
        return false;
    }

    /**
     * 单个KEY/VALUE 获取值
     */
    public static String get(String key) {
        Jedis jedis = getJedis();
        if (jedis == null) {
            return null;
        }
        String result = null;
        try {
            result = jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            close(jedis);
        }
        return result;
    }

    /**
     * 多个KEY/VALUE 批量设置值
     */
    public static boolean setSnapshotValues(List<RealTimeData> realTimeDataList) {
        if (CollectionUtils.isEmpty(realTimeDataList)) {
            return false;
        }
        Jedis jedis = getJedis();
        if (jedis == null) {
            return false;
        }
        String[] keysValues = new String[realTimeDataList.size() * 2];
        for (int i = 0; i < realTimeDataList.size(); i++) {
            keysValues[i * 2] = realTimeDataList.get(i).getName();
            keysValues[(i * 2) + 1] = JSON.toJSONString(realTimeDataList.get(i));
        }
        try {
            String result = jedis.mset(keysValues);
            if ("OK".equals(result)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            close(jedis);
        }
        return false;
    }

    /**
     * 多个KEY/VALUE 批量获取值
     */
    public static Map<String, RealTimeData> getSnapshotValues(Long companyId, List<String> keyList) {
        // 若所查询测点为空,则直接退出
        if (CollectionUtils.isEmpty(keyList)) {
            return null;
        }
        // 从连接池中获取Jedis
        Jedis jedis = getJedis();
        if (jedis == null) {
            return null;
        }
        try {
            // 创建数据查询返回实体
            Map<String, RealTimeData> rtnMap = new HashMap<>();
            // 批量获取数据
            List<String> result = jedis.mget(keyList.toArray(new String[0]));
            // 赋值,KV
            for (int i = 0; i < keyList.size(); i++) {
                if (CollectionUtils.isEmpty(result)) {
                    rtnMap.put(keyList.get(i), null);
                } else {
                    String jsonValue = result.get(i);
                    RealTimeData realTimeData = StringUtils.isNotEmpty(jsonValue) ? JSON.parseObject(jsonValue, RealTimeData.class) : null;
                    rtnMap.put(keyList.get(i), realTimeData);
                }
            }
            return dealRealTimeDataPoint(companyId, keyList, rtnMap);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return null;
        } finally {
            // 关闭Jedis
            close(jedis);
        }
    }

    /**
     * 处理小数点
     */
    public static Map<String, RealTimeData> dealRealTimeDataPoint(Long companyId, List<String> keyList, Map<String, RealTimeData> realTimeDataMap) {
        // 获取测点详细数据
        List<Station> stationList = stationDao.getStationListByNameList(companyId, keyList);
        // 处理小数点
        mapFor:
        for (Map.Entry<String, RealTimeData> dataEntry : realTimeDataMap.entrySet()) {
            // 获取测点数据
            RealTimeData realTimeData = dataEntry.getValue();
            if (realTimeData == null) {
                continue;
            }
            // 遍历测点,匹配测点数据
            for (Station station : stationList) {
                // 若匹配到
                if (dataEntry.getKey().equals(station.getKey())) {
                    realTimeData.setValue(TypeChangeUtils.parsePoint(Double.parseDouble(realTimeData.getValue()), StringUtils.isEmpty(station.getDecimalDigits()) ? 0 : Integer.parseInt(station.getDecimalDigits())));
                    continue mapFor;
                }
            }
            realTimeData.setValue(TypeChangeUtils.parsePoint(Double.parseDouble(realTimeData.getValue()), 0));
        }
        return realTimeDataMap;
    }

    /**
     * 发布
     */
    public static void publish(String channel, String message) {
        // 从连接池中获取Jedis
        Jedis jedis = getJedis();
        if (jedis == null) {
            return;
        }
        jedis.publish(channel, message);
    }

    // ###########################################################################################################
    // HASH
    // ###########################################################################################################

    /**
     * 同时将多个 field-value (域-值)对设置到哈希表 key 中。
     */
    public static boolean hmset(String key, Map<String, String> hash) {
        // 从连接池中获取Jedis
        Jedis jedis = getJedis();
        if (jedis == null) {
            return false;
        }
        try {
            String result = jedis.hmset(key, hash);
            if ("OK".equals(result)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            // 关闭Jedis
            close(jedis);
        }
        return false;
    }

    /**
     * 获取哈希表中所有值。
     */
    public static List<String> hvals(String key) {
        // 从连接池中获取Jedis
        Jedis jedis = getJedis();
        if (jedis == null) {
            return null;
        }
        try {
            return jedis.hvals(key);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return null;
        } finally {
            // 关闭Jedis
            close(jedis);
        }
    }

    /**
     * 删除一个哈希表字段
     */
    public static boolean hdel(String key, String field) {
        // 从连接池中获取Jedis
        Jedis jedis = getJedis();
        if (jedis == null) {
            return false;
        }
        try {
            return jedis.hdel(key, field) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            // 关闭Jedis
            close(jedis);
        }
        return false;
    }

    /**
     * 获取所有给定字段的值
     */
    public static List<String> hmget(String key, String... fields) {
        // 从连接池中获取Jedis
        Jedis jedis = getJedis();
        if (jedis == null) {
            return null;
        }
        try {
            return jedis.hmget(key, fields);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            // 关闭Jedis
            close(jedis);
        }
    }

}

你可能感兴趣的:(redis,java,缓存)