1,配置文件

  redis:clusterNodes:- 10.108.6.90:6179- 10.108.6.90:6279- 10.108.6.90:6379- 10.108.6.90:6479- 10.108.6.90:6579- 10.108.6.90:6679password: Allways_123expireSeconds: 120commandTimeout: 10000 #redis操作的超时时间pool:#最大连接数maxActive: 5000#最大空闲连接数maxIdle: 30#最小空闲连接数minIdle: 5#获取连接最大等待时间 ms #default -1maxWait: 10000#最大尝试连接数maxAttempts: 1  

2,java属性对象创建

@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {private int expireSeconds;private List<String> clusterNodes = new ArrayList<String>();private String password;private int commandTimeout;private Map<String,Integer> pool = new HashMap<>();public int getExpireSeconds() {return expireSeconds;}public void setExpireSeconds(int expireSeconds) {this.expireSeconds = expireSeconds;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public int getCommandTimeout() {return commandTimeout;}public void setCommandTimeout(int commandTimeout) {this.commandTimeout = commandTimeout;}public Map<String, Integer> getPool() {return pool;}public void setPool(Map<String, Integer> pool) {this.pool = pool;}public List<String> getClusterNodes() {return clusterNodes;}public void setClusterNodes(List<String> clusterNodes) {this.clusterNodes = clusterNodes;}
}

3,java获取配置文件信息

@Configuration
public class JedisClusterConfig {@Autowiredprivate RedisProperties redisProperties;/*** 返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用* @return*/@Beanpublic JedisCluster getJedisCluster() {Set<HostAndPort> nodes = new HashSet<>();List<String> clusterNodes = redisProperties.getClusterNodes();for (String ipPort : clusterNodes) {String[] ipPortPair = ipPort.split(":");nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));}GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();poolConfig.setMaxTotal(redisProperties.getPool().get("maxActive"));//最大连接数poolConfig.setMaxIdle(redisProperties.getPool().get("maxIdle"));//最大空闲连接数poolConfig.setMinIdle(redisProperties.getPool().get("minIdle"));//最小空闲连接数poolConfig.setMaxWaitMillis(redisProperties.getPool().get("maxWait").longValue());//连接最大等待时间return new JedisCluster(nodes,redisProperties.getCommandTimeout(),redisProperties.getCommandTimeout(),redisProperties.getPool().get("maxAttempts"),redisProperties.getPassword() ,poolConfig);//需要密码连接的创建对象方式}
}

4,工具类

package com.anji.allways.common.redis;import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.TreeSet;/*** <pre>* redis工具类* </pre>** @author 超级家明* @version $Id: RedisUtils.java, v 0.1 2018年7月6日 下午3:39:13 超级家明 Exp $*/
@Component
public class RedisUtils {public static String                   REDIS_RECEIVE = "receive_";private static String redisCode = "utf-8";public static String                     REDIS_OURINV = "outinv_synchronized";private static final Long RELEASE_SUCCESS = 1L;public final static Logger logger = LogManager.getLogger(RedisUtils.class);@Autowiredprivate JedisCluster jedisCluster;/*** 设置缓存** @param key   缓存key* @param value 缓存value*/public void set(String key, String value) {jedisCluster.set(key, value);}/*** 设置缓存,并且自己指定过期时间** @param key* @param value* @param expireTime 过期时间*/public void setWithExpireTime(String key, String value, int expireTime) {jedisCluster.setex(key, expireTime, value);}/*** 设置失效时间** @param key* @param expireTime*/public void expire(String key, int expireTime) {jedisCluster.setex(key, expireTime, jedisCluster.get(key));}/*** 获取指定key的缓存** @param key*/public String get(String key) {String value = jedisCluster.get(key);return value;}//解决redis异常public String getThrowRedis(String key) {try {get(key);} catch (Exception e) {return null;}return get(key);}/*** 设置缓存对象** @param key        缓存key* @param obj        缓存value* @param expireTime 过期时间*/public <T> void setObject(String key, T obj, int expireTime) {jedisCluster.setex(key, expireTime, JSON.toJSONString(obj));}/*** 获取指定key的缓存** @param key---JSON.parseObject(value, User.class);*/public String getObject(String key) {return jedisCluster.get(key);}/*** 判断当前key值 是否存在** @param key*/public boolean hasKey(String key) {return jedisCluster.exists(key);}/*** 删除指定key的缓存** @param key*/public void delete(String key) {jedisCluster.del(key);}/*** <pre>* 上锁* </pre>** @param key*/public synchronized void lock(String key) {if (StringUtils.isBlank(key)) {return;}this.set(key, new Date().toString());}/*** <pre>* 上锁* </pre>** @param key*/public synchronized void lockWithExpireTime(String key, int seconds) {if (StringUtils.isBlank(key)) {return;}jedisCluster.setex(key, seconds, new Date().toString());}/*** <pre>* 判断key是否被锁住了* </pre>** @param key* @return*/public synchronized Boolean isLock(String key) {if (StringUtils.isBlank(key)) {return false;}String stringDate = this.get(key);if (StringUtils.isBlank(stringDate)) {return false;}return true;}/*** <pre>* 解锁* </pre>** @param key*/public synchronized void unLock(String key) {if (StringUtils.isBlank(key)) {return;}this.delete(key);}/*** <pre>* 递增* </pre>** @param key* @param by* @return*/public Long incr(String key, Long by) {//默认原子操作if (by == null) {by = 1l;}return jedisCluster.incrBy(key, by);}/*** <pre>** </pre>** @param key* @param value* @param liveTime*/public void set(String key, Object value, Long liveTime) {try {jedisCluster.setex(key.getBytes(redisCode), liveTime.intValue(), value.toString().getBytes(redisCode));} catch (UnsupportedEncodingException e) {e.printStackTrace();}}/*** <pre>* 批量删除keys* </pre>** @param keys*/public void delKeys(String[] keys) {if(keys != null) {for (String key : keys) {Long del = jedisCluster.del(key);System.out.println(del);}}}public void unlockValue(String keys, String value) {String lockValue = jedisCluster.get(keys);if (lockValue.equals(value)){jedisCluster.del(keys);}}public String[] keys(String pattern){TreeSet<String> keys = new TreeSet<>();Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();for(String k : clusterNodes.keySet()){logger.debug("Getting keys from: {}", k);JedisPool jp = clusterNodes.get(k);Jedis connection = jp.getResource();try {keys.addAll(connection.keys(pattern));} catch(Exception e){logger.error("Getting keys error: {}", e);} finally{logger.debug("Connection closed.");connection.close();//用完一定要close这个链接!!!}}return keys.toArray(new String[] {});}/*** 设置缓存* @param key 缓存key* @param value 缓存value*/public Long setnx(String key, String value) {return jedisCluster.setnx(key, value);}/*** <pre>* 上锁* </pre>** @param key*/public synchronized boolean locknx(String key){if(StringUtils.isBlank(key)){return false;}Long result = this.setnx(key, new Date().toString());if(result.equals(0L)){//如果返回0 则该key已经存在return false;}return true;}/*** <pre>* 上锁* </pre>** @param key*/public synchronized boolean locknx(String key, String value){if(StringUtils.isBlank(key)){return false;}Long result = this.setnx(key, value);if(result.equals(0L)){//如果返回0 则该key已经存在return false;}this.expire(key, 60*3);//设置失效时间3分钟return true;}public synchronized boolean lock(String lockKey,String requestId,int expireTime) {String result=jedisCluster.set(lockKey, requestId, "NX", "PX", expireTime);if("OK".equals(result)) {return true;}return false;}public synchronized boolean releaseLock(String lockKey,String requestId) {String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";Object result = jedisCluster.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));if (RELEASE_SUCCESS.equals(result)) {return true;}return false;}
}

springboot-redis读取配置文件相关推荐

  1. SpringBoot如何读取配置文件(@Value/@ConfigurationProperties/Environment)

    [版权申明] 非商业目的注明出处可自由转载 博文地址:https://blog.csdn.net/ShuSheng0007/article/details/117002443 出自:shusheng0 ...

  2. Wagon部署springboot项目读取配置文件错误问题

    wagon(瓦工)插件是一个很不错的轻量级,快速部署项目到服务器的插件,针对用中小项目,使用起来十分方便.今天跟大家分享一下自己在使用过程中遇到的一个坑,持续两天时间都没能够解决,最终在多方求助下找到 ...

  3. boot idea无法识别spring_intellij idea springboot无法读取配置文件的解决方法

    问题分析及解决方案 问题原因: Mybatis没有找到合适的加载类,其实是大部分spring - datasource - url没有加载成功,分析原因如下所示. DataSourceAutoConf ...

  4. 读取文档时出现问题129_springboot读取配置文件的自定义内容时出现中文乱码

    学习springboot时读取配置文件自定义内容出现中文乱码总结. 方法一: Windowd→Preferences→General→Editors→Text Editors→Spelling里面的E ...

  5. SpringBoot 读取配置文件中参数全面教程

    一.简介 在日常开发使用 SpringBoot 框架时,经常有一些配置信息需要放置到配置文件中,我们需要手动读取这些配置到应用中进行一些逻辑,这里整理了一些常用读取配置的方法,简单介绍一下. 1.Sp ...

  6. springboot 的两种配置文件语法||配置文件占位符||@Value 读取配置文件及验证处理

    [掌握]springboot 的两种配置文件语法 导入配置文件自动提示的包 创建 Student 类 创建修改 application.properties 配置文件占位符 ${random.int} ...

  7. Spring-boot中读取config配置文件的两种方式

    了解过spring-Boot这个技术的,应该知道Spring-Boot的核心配置文件application.properties,当然也可以通过注解自定义配置文件的信息. Spring-Boot读取配 ...

  8. 超简单:解析 yml 类型(application.yml)配置文件 、springboot 工程读取 yml 文件中的值

    方法三是我觉得最简单的. 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家.点击跳转到教程. 1. 工程结构: 2. 我要读取  application.yml 中属性 ...

  9. Springboot中,如何读取配置文件中的属性

    摘要:在比较大型的项目的开发中,比较经常修改的属性我们一般都是不会在代码里面写死的,而是将其定义在配置文件中,之后如果修改的话,我们可以直接去配置文件中修改,那么在springboot的项目中,我们应 ...

  10. 在springboot中,如何读取配置文件中的属性

    摘要:在比较大型的项目的开发中,比较经常修改的属性我们一般都是不会在代码里面写死的,而是将其定义在配置文件中,之后如果修改的话,我们可以直接去配置文件中修改,那么在springboot的项目中,我们应 ...

最新文章

  1. 自定义Realm实现认证
  2. 学习MSCKF笔记——真实状态、标称状态、误差状态
  3. 2004-5-12+ 用DataSet实现分页
  4. AppiumDriver java部分api
  5. 批量删除Excel文档中的超链接
  6. android 弹出弹框2秒消失_基于HTML5 Canvas 实现弹出框
  7. 用Java的Set实现交并差等集合运算
  8. spark DAGScheduler、TaskSchedule、Executor执行task源码分析
  9. (12)ISE14.7仿真流程(FPGA不积跬步101)
  10. virtualenv之python虚拟环境
  11. XSSFWorkbook 设置单元格样式_openpyxl3.0官方文档(25)—— 使用样式
  12. 几款查看dll和exe信息的小工具
  13. FileZilla Server + FlashFXP 快速傻瓜式搭建FTP服务
  14. win7安装OneNote
  15. 模拟调节器和数字计算机如何实现PID控制,模拟PID-调节器设计及数字化实现.doc...
  16. 鼠标右键转圈圈_【鼠标右键一直在转圈圈】鼠标右键一直在闪_鼠标一直在转圈圈...
  17. 新百家姓出来了,看你排第几位?
  18. EMC 2 完美的EMC电路设计攻略之:元器件选型(上)
  19. c程序设计语言k rpdf,《C程序设计语言》(KR)中文高清非扫描件
  20. .flo 文件转换为.png 文件 ; matlab 读取 .ppm 和 .flo 文件

热门文章

  1. 【angularjs】pc端使用angular搭建项目,实现导出excel功能
  2. 云上DevOps-CodePipeline,Packer和Terraform集成实践探索
  3. 是否采用SD-WAN?你需要先考虑以下问题
  4. swift流行UI库(github)
  5. Android 学习之Fragment生命周期
  6. KVM 介绍(3):I/O 全虚拟化和准虚拟化 [KVM I/O QEMU Full-Virtualizaiton Para-virtualization]
  7. 数据包的分类和调度-Linux TC的另一种解释
  8. 内核抢占机制(preempt)
  9. JAVA小白启蒙篇:第一个SSM框架搭建示例(附源码下载)
  10. linux缺页异常处理--内核空间