基于数组阻塞队列 ArrayBlockingQueue 的一个队列工具类
java语言基于ArrayBlockingQueue 开发的一个根据特定前缀和后缀的队列。每天自动循环生成。
1.定义队列基类 Cookie
package com.bytter.util.queue; import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue; public class Cookie {
private ArrayBlockingQueue<String> queue;
private int cursor = 1;
private Date date = new Date();
private int maxPoolQueue = 500;
private int mixPoolQueue = 100; public Cookie(int maxPoolQueue,int mixPoolQueue,Date date){
this.maxPoolQueue=maxPoolQueue;
this.mixPoolQueue=mixPoolQueue;
this.date=date;
this.queue = new ArrayBlockingQueue<String>(this.maxPoolQueue,true);
} public Cookie(int maxPoolQueue,int mixPoolQueue,Date date, int cursor){
this.maxPoolQueue = maxPoolQueue;
this.mixPoolQueue = mixPoolQueue;
this.date=date;
this.cursor=cursor;
this.queue = new ArrayBlockingQueue<String>(this.maxPoolQueue,true);
} public ArrayBlockingQueue<String> getQueue() {
return queue;
} public Cookie setQueue(ArrayBlockingQueue<String> queue) {
this.queue = queue;
return this;
} public int getCursor() {
return cursor;
} public Cookie setCursor(int cursor) {
this.cursor = cursor;
return this;
} public Date getDate() {
return date;
} public Cookie setDate(Date date) {
this.date = date;
return this;
} public int getMaxPoolQueue() {
return maxPoolQueue;
} public Cookie setMaxPoolQueue(int maxPoolQueue) {
this.maxPoolQueue = maxPoolQueue;
return this;
} public int getMixPoolQueue() {
return mixPoolQueue;
} public Cookie setMixPoolQueue(int mixPoolQueue) {
this.mixPoolQueue = mixPoolQueue;
return this;
} }
2.QueueUtil 队列工具类,用于获取队列中的值(主要是获取付款的单号==)
package com.bytter.util.queue; import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import com.bytter.framework.persistence.dao.IBaseDAO;
import com.bytter.util.AppContextUtil;
import com.bytter.util.DateUtil;
/**
*
* @author
* May 6, 2019 10:35:39 AM
* @version
*/
public class QueueUtil{ private static Logger log = LogManager.getLogger(QueueUtil.class);
protected static IBaseDAO baseDao = null;
private static ConcurrentHashMap<String, Cookie> queueMap = new ConcurrentHashMap<String, Cookie>(); private static class SingletonClassInstance{
private static final QueueUtil instance=new QueueUtil();
} private QueueUtil(){} public static QueueUtil getInstance(){
return SingletonClassInstance.instance;
} /**
* 调用事例: QueueUtil.getInstance().getSequence(SequenceEnum.BIS_EXC)
* @param sequenceEnum
* @return
* @throws InterruptedException
*/
@SuppressWarnings("unchecked")
public String getSequence(SequenceEnum sequenceEnum) throws InterruptedException{
String value = "";
String key = sequenceEnum.getTableName()+"_"+sequenceEnum.getFieldName();
Cookie cookie = queueMap.get(key);
value = cookie.getQueue().take();
String returnValue = sequenceEnum.getPrefix()+DateUtil.dateToStr(sequenceEnum.getDateFormat(), new Date());
for (int i = 0; i < sequenceEnum.getSequenceLength()-value.length(); i++) {
returnValue += "0";
}
returnValue += value;
log.info("取出的单号:"+returnValue);
return returnValue;
} public void initQueue() {
putAllMap();
Thread thread = new Produce(queueMap);
thread.setName("QueueUtil_Produce");
thread.start();
} private static void putAllMap() {
queueMap.clear();
int curor = 1;
log.info("-----开始加载队列 -------");
for (SequenceEnum sequenceEnum : SequenceEnum.values()){
String key = sequenceEnum.getTableName()+"_"+sequenceEnum.getFieldName();
//同一天但是系统重启或者宕机的情况时,游标重置为1.此时需要查询表中最大的值并且置游标值+1
String sql="SELECT MAX("+sequenceEnum.getFieldName()+") FROM "+sequenceEnum.getTableName()+" WHERE "+sequenceEnum.getFieldName()+" LIKE '"+sequenceEnum.getPrefix()+"%'";
List list = baseDao.search_sql(null, sql, "", "", null);
if(list != null && list.size() >0 && list.get(0) != null){
String no = list.get(0).toString();
//单号,自增。
String count = no.substring(no.length()-sequenceEnum.getSequenceLength());
String date = no.replaceAll(count, "").replaceAll(sequenceEnum.getPrefix(), "");
/*if(date.equals(DateUtil.dateToStr(sequenceEnum.getDateFormat(), new Date()))){
curor = Integer.parseInt(count) + 1;
}*/
}
log.info("加载队列 :table=="+sequenceEnum.getTableName()+" field=="+sequenceEnum.getFieldName()+" 游标=="+curor);
queueMap.put(key, new Cookie(sequenceEnum.getMaxSeqSize(),sequenceEnum.getMinSeqSize(),new Date(),curor));
}
log.info("-----队列加载完毕 -------");
} static{
baseDao = AppContextUtil.getBean("baseDao");
//第一次调用时开启队列
//initQueue();
} }
3.生产者线程类
package com.bytter.util.queue; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap; import com.bytter.util.DateUtil; public class Produce extends Thread{
private ConcurrentHashMap<String, Cookie> queueMap;
public Produce(ConcurrentHashMap<String, Cookie> queueMap){
this.queueMap=queueMap;
}
public void run(){
ArrayBlockingQueue<String> queue;
int mixSize;
int curor;
Cookie cookie;
Date date;
Map.Entry<String,Cookie> entry;
Iterator<Map.Entry<String,Cookie>> iteratorMap;
while (true) {
iteratorMap = queueMap.entrySet().iterator();
while (iteratorMap.hasNext()){
entry = iteratorMap.next();
cookie = entry.getValue();
queue = cookie.getQueue();
mixSize = cookie.getMixPoolQueue();
curor = cookie.getCursor();
date = cookie.getDate();
//新的一天,游标开始重置
if(!DateUtil.dateToStr("yyyy-MM-dd", new Date()).equals(DateUtil.dateToStr("yyyy-MM-dd", date))){
curor = 1;
queue.clear();
date = new Date();
System.out.println("重置游标时间===="+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
} //offer 在填满后返回false
if(queue.size() < mixSize){
while (queue.offer(curor + "")) {
curor++;
}
}
cookie.setQueue(queue).setCursor(curor).setDate(date);
queueMap.put(entry.getKey(),cookie);
}
}
}
}
4.自定义的生成单号的规则枚举类
package com.bytter.util.queue;
public enum SequenceEnum{
/**
* 付款指令编码 yyMMdd000001
* @return
*/
BIS_EXC("",6, "BIS_EXC", "VOUCHER_NO", "yyMMdd",500,100),
/**
* 付款单号
* @return
*/
PAYMENT_BILL_NO("P",7, "T_BIS_PAYMENT_INFO", "BILL_CODE", "yyMMddHHmmss",500,100), ; /**
* 流水号前缀
*/
private String prefix; /**
* 流水号数字部分长度
*/
private Integer sequenceLength;
/**
* 业务表名
*/
private String tableName;
/**
* 业务表中的字段名
*/
private String fieldName;
/**
* 日期格式化模板
*/
private String dateFormat; /**
* 队列最大的长度
*/
private int maxSeqSize;
/**
* 队列最小长度
*/
private int minSeqSize; /**
* @param prefix 流水号前缀
* @param sequenceLength 流水号自增长长度
* @param tableName 表名
* @param fieldName 字段名
* @param dateFormat 日期格式化模板
*/
SequenceEnum(String prefix, Integer sequenceLength, String tableName, String fieldName,String dateFormat,int maxSeqSize,int minSeqSize) {
this.prefix = prefix;
this.sequenceLength = sequenceLength;
this.tableName = tableName;
this.fieldName = fieldName;
this.dateFormat = dateFormat;
this.maxSeqSize = maxSeqSize;
this.minSeqSize = minSeqSize;
} /**
* @param prefix 流水号前缀
* @param sequenceLength 流水号自增长长度
* @param tableName 表名
* @param fieldName 字段名
* @param dateFormat 日期格式化模板
*/
SequenceEnum(Integer sequenceLength, String tableName, String fieldName,String dateFormat) {
this.sequenceLength = sequenceLength;
this.tableName = tableName;
this.fieldName = fieldName;
this.dateFormat = dateFormat;
} public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public Integer getSequenceLength() {
return sequenceLength;
}
public void setSequenceLength(Integer sequenceLength) {
this.sequenceLength = sequenceLength;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
} public String getDateFormat() {
return dateFormat;
} public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
} public int getMaxSeqSize() {
return maxSeqSize;
} public void setMaxSeqSize(int maxSeqSize) {
this.maxSeqSize = maxSeqSize;
} public int getMinSeqSize() {
return minSeqSize;
} public void setMinSeqSize(int minSeqSize) {
this.minSeqSize = minSeqSize;
} }
5.测试相关类
1> 消费者线程
package com.bytter.util.queue;
public class implements Runnable{
public void run(){
try {
for (int i = 0; i < 200; i++) {
Thread.sleep(Long.valueOf((long) (Math.random()*10*300)));
// System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName()+"==="+SequenceUtilTest.getInstance().getSequence(SequenceEnum.BIS_EXC));
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
2>测试main 方法
package com.bytter.util.queue;
public class tests {
public static void main(String[] args) throws InterruptedException {
new Thread(new Consume()).start();
new Thread(new Consume()).start();
new Thread(new Consume()).start();
new Thread(new Consume()).start();
new Thread(new Consume()).start();
// new Thread(new Consume()).start();
// new Thread(new Consume()).start();
// new Thread(new Consume()).start();
// new Thread(new Consume()).start();
// new Thread(new Consume()).start();
}
}
基于数组阻塞队列 ArrayBlockingQueue 的一个队列工具类的更多相关文章
- Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!
Go/Python/Erlang编程语言对比分析及示例 本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...
- 编写Java程序,创建一个数学工具类,将该类设计为final类,Final 修饰符的使用。
返回本章节 返回作业目录 需求说明: 创建一个数学工具类. 将该类设计为final类. 将该类的构造方法的访问权限定义为私有,以防止外界实例化该类. 在该类定义静态double类型常量π,其值为3.1 ...
- 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; usi ...
- 分享一个Snackbar工具类 SnackbarUtils;
分享一个Snackbar工具类,源代码也是在Github上面找的,自己做了一下修改: 功能如下: 1:设置Snackbar显示时间长短 1.1:Snackbar.LEN ...
- java中定义一个CloneUtil 工具类
其实所有的java对象都可以具备克隆能力,只是因为在基础类Object中被设定成了一个保留方法(protected),要想真正拥有克隆的能力, 就需要实现Cloneable接口,重写clone方法.通 ...
- 手写一个LRU工具类
LRU概述 LRU算法,即最近最少使用算法.其使用场景非常广泛,像我们日常用的手机的后台应用展示,软件的复制粘贴板等. 本文将基于算法思想手写一个具有LRU算法功能的Java工具类. 结构设计 在插入 ...
- [分享]一个String工具类,也许你的项目中会用得到
每次做项目都会遇到字符串的处理,每次都会去写一个StringUtil,完成一些功能. 但其实每次要的功能都差不多: 1.判断类(包括NULL和空串.是否是空白字符串等) 2.默认值 3.去空白(tri ...
- 调用CMD命令的一个.NET工具类(MyWindowsCmd)
功能大概描述一下如果直接StandardOutput.ReadToEnd()这种方法,有很多限制 这类方式必须把命令全部执行一次写入并标记为exit,而且返回内容的获取会一直等待,如果在主线程里使用会 ...
- 分享一个FileUtil工具类,基本满足web开发中的文件上传,单个文件下载,多个文件下载的需求
获取该FileUtil工具类具体演示,公众号内回复fileutil20200501即可. package com.example.demo.util; import javax.servlet.htt ...
随机推荐
- [题解][洛谷]_U75702/P5462_X龙珠_论何为字典序
赛时嫌麻烦,没写 赛后自闭了,写了一下午 题目描述 “X龙珠”是一款益智小游戏.游戏中有 n(2|n)n(2∣n) 个编号互不相同龙珠按照给定的顺序排成一个队列,每个龙珠上面都有一个编号.每次操作时, ...
- chromedriver.exe下载
淘宝的镜像地址可以下载: https://npm.taobao.org/mirrors/chromedriver/
- 786B - Legacy(线段树 + 最短路)线段树优化建图
题意: 就是给定一张n nn个点的图,求源点s ss到每个点的单源最短路.这张图共有q组边,连边方式有3种: a→b ,边权为w的单向边:a→[l,r] ,即a到连续区间[l,r]中的每一个点都有一条 ...
- 剑指offer-数组中的逆序对-数组-python
题目描述 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对.输入一个数组,求出这个数组中的逆序对的总数P.并将P对1000000007取模的结果输出. 即输出P%1000 ...
- 普通交叉验证(OCV)和广义交叉验证(GCV)
普通交叉验证OCV OCV是由Allen(1974)在回归背景下提出的,之后Wahba和Wold(1975)在讨论 了确定多项式回归中多项式次数的背景,在光滑样条背景下提出OCV. Craven和Wa ...
- ORA-01846: 周中的日无效
参考这篇博客:https://blog.csdn.net/yabingshi_tech/article/details/8678218
- 在mybatis中,在列表分页查询过程中造成集合属性数据丢失的问题
由于在进行多表关联分页查询时,某一个集合属性的多条数据正好位于2页的分割处,那么就会造成在前一页获取到的该集合属性的集合内部数据不全,因为其余数据被分到了第二页, 因此建议在进行集合属性的封装时,最好 ...
- 可以提升幸福感的js小技巧(下)
4.数字 4.1 不同进制表示法 ES6中新增了不同进制的书写格式,在后台传参的时候要注意这一点. 29 // 10进制 035 // 8进制29 原来的方式 0o35 // 8进制29 ES6的方式 ...
- MySQL安装+Navicat_Premium(安装+破解)+Navicat_Premium中MySQL的localhost不能正常连接+不能连接Docker启动容器中的MySQL
MySQL安装 安装MySQL 我这里安装的是 MySQL 8.0 Command Line Client 下载+安装 详情见 https://www.cnblogs.com/taopanfeng/p ...
- SpringBoot封装自己的Starter
https://juejin.im/post/5cb880c2f265da03981fc031 一.说明 我们在使用SpringBoot的时候常常要引入一些Starter,例如spring-boot- ...