目录
4. RunTime.getRunTime().addShutdownHook
5. Map使用(toString与JSONObject.toJSONString)
1. ScheduleThreadPoolExecutor
可以实现定时任务的线程池
execute()、submit() -零延时
schedule()-延时一定时间后执行
scheduleAtFixedRate()-周期性延时:从上一周期的任务开始时间到当前周期的任务开始时间的间隔;
scheduleWithFixedDelay()-周期性延时: 从上一周期的任务的执行结束时间到当前周期的任务开始时间的间隔。
2. 单例模式
参考网站:单例模式 | 菜鸟教程
public class SingleObject {
//创建 SingleObject 的一个对象
private static SingleObject instance = new SingleObject();
//让构造函数为 private,这样该类就不会被实例化
private SingleObject(){}
//获取唯一可用的对象
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello World!");
}
}
简单来说,单例模式就是,一个类只能实例化一次,不能多次实例化。如上:类SingleObject(单例模式),使用SingleObject object = SingleObject.getInstance(),便实现了一次实例化,又因new SingleObject是static,所以这个实例会在静态存储区,每次使用这个实例时,都会调用同一个实例。
3. 工厂模式
简单的讲:将多个类(A1,A2,A3)放在一个类(B)中进行统一管理。使用这些类(A1,A2,A3)时,通过B进行调用,调用时以不同的标志加以区分。
这里B就是一个工厂类。B类的(构造)函数中一般包含了对类(A1,A2,A3)的实例化代码,这样就可以用B调(A1,A2,A3)。
如下:对Rectangle类和Circle类用一个工厂类进行管理。
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
工厂类
public class ShapeFactory {
//使用 getShape 方法获取形状类型的对象
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}
return null;
}
}
调用时,只需要使用ShapeFactory的实例shapeFactory.getShape("Circle")或者shapeFactory.getShape("Rectangle")即可。
4. RunTime.getRunTime().addShutdownHook
参考网站:RunTime.getRunTime().addShutdownHook用法 - kabibo - 博客园
在jvm中增加一个关闭的钩子,当jvm关闭的时候,会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子,当系统执行完这些钩子后,jvm才会关闭。
所以这些钩子可以在jvm关闭的时候进行内存清理、对象销毁等操作。(简单地说,程这个钩子函数在java虚拟机停用前执行,多线程的最后执行)
5. Map使用(toString与JSONObject.toJSONString)
Map<String,Double> map = new HashMap<>();
map.put("test1",1.0);
map.put("test2",2.0);
System.out.println(map.toString);//结果:"{test1=1.0,test2=2.0}",这种方式不好转回map,需要先split掉逗号,再去掉=;
System.out.println(JSONObject.toJSONString(map));
//结果:"{test1:1.0,test2=2.0}"。这里转回map,可以直接用JSONObject.parseObject(JSONObject.toJSONString(map),Map.class);
6. iframe高度自适应
解释:也就是iframe中嵌入的html网页全部显示,不出现滚动条,滚动条依赖自己添加的
<iframe class="menu-content-detail"
:src="url"
scrolling="no"
frameborder="0" id="iframe">
</iframe>
..............此处省略若干行....................
mounted() {
this.iframeHeightSet()
},
..............此处省略若干行....................
iframeHeightSet() {
const that = this
this.$nextTick(() => {
// iframe加载完成之后获取高度
const iframe = document.querySelector('#iframe')
if (iframe.attachEvent) {
iframe.attachEvent('onload', function() {
const clientHeight = iframe.contentDocument.documentElement.clientHeight
const scrollHeight = iframe.contentDocument.documentElement.scrollHeight
that.$refs.main_page_iframe.style.height = Math.max(clientHeight, scrollHeight) + 'px'
})
} else {
iframe.onload = function() {
const clientHeight = iframe.contentDocument.documentElement.clientHeight
const scrollHeight = iframe.contentDocument.documentElement.scrollHeight
that.$refs.main_page_iframe.style.height = Math.max(clientHeight, scrollHeight) + 'px'
}
}
})
}
7. @Transactional对应的pom
import org.springframework.transaction.annotation.Transactional;
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.0</version>
</dependency>
前两个是用来mysql连接的,第3个是加事务注解的
8. 使用Telnet监测端口可用性
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
public class TelnetUtil {
/**
* 通过telnet探测ip:port可用性
* @param hostname
* @param port
* @param timeout
* @return
* @throws IOException
*/
public static boolean telnet(String hostname, int port, int timeout) throws IOException {
Socket socket = new Socket();
boolean isConnected = false;
try {
socket.connect(new InetSocketAddress(hostname, port), timeout);
isConnected = socket.isConnected();
} catch (IOException e) {
throw new IOException(e);
}finally{
try {
socket.close();
} catch (IOException e) {
throw new IOException(e);
}
}
return isConnected;
}
}
9. el-input只允许输入数字
<!--只允许输入6位整数-->
<el-input placeholder="只允许输入数字"
oninput="value=value.replace(/[^\d]/g,'')" maxLength='6'
v-model="query.port">
</el-input>
<!--只允许输入6位小数-->
<el-input v-model="query.port"
oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0)
{value=value.slice(0,value.indexOf('.')+3)}"
maxLength='9'
</el-input>
10.正则表达式
以指定字符串startString开头,指定字符串endString结尾
-
"startString([\\s\\S]*?)endString"
- " (startString)(.*?)(endString)"
java正则表达式匹配反斜杠:
比如要匹配出"END_POS":"24614\",中的24614。
String endPosRegex = "\"END_POS\":\"([\\s\\S]*?)\\\\\",";
Pattern endPosPattern = Pattern.compile(endPosRegex);
Matcher endPosMatcher = endPosPattern.matcher(recordString);
while (endPosMatcher.find()) {
String endPos = endPosMatcher.group(1);
metadataSyncMetrics.setEndPos(Integer.valueOf(endPos));
}
在endPosRegex中最后包含5个反斜杠,"\\"表示一个"\",在java中一个"\"也要用"\\"表示。这样,第1、2位置的"\\"代表endPosRegex中的"\",第3、4位置的"\\"代表java中的"\",第5位置用于转义后引号"。
11.el-table滚动条样式修改
/deep/ .el-table{
background-color: transparent;
color: #d3dce6;
}
/deep/ .el-table__body-wrapper::-webkit-scrollbar{
width:5px
}
/deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb{
background-color: rgba(200,200,200,0.8);
border-radius: 10px;
}
/deep/ .el-table tbody tr:hover>td{
background-color: transparent;
}
/deep/ .el-table th,
/deep/ .el-table tr,
/deep/ .el-table td{
background-color: transparent;
border: none;
}
/deep/ .el-table thead{
color: #ffffff;
font-size: 16px;
}
/deep/ .el-table::before{
left: 0;
bottom: 0;
width: 100%;
height: 0;
}
12.echart绘制
vue示例:需要给出图片的width与height,不然无法显示
<template>
<div id="main" style="width: 610px;height: 360px;padding-top: 20px"></div>
</template>
<script>
export default {
name: "main",
data() {
return {
}
},
props: {
queryParam: Object
},
watch: {
//深度监听(解决了值刷新不及时的问题)
queryParam: {
handler: function (newVal, oldVal) {
this.drawPie()
},
deep: true
},
},
mounted() {
this.drawPie();
},
methods: {
drawPie() {
import * as echarts from 'echarts';
var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;
option = {
title: {
text: '某站点用户访问来源',
subtext: '纯属虚构',
left: 'center'
},
tooltip: {
trigger: 'item'
},
legend: {
orient: 'vertical',
left: 'left',
},
series: [
{
name: '访问来源',
type: 'pie',
radius: '50%',
data: [
{value: 1048, name: '搜索引擎'},
{value: 735, name: '直接访问'},
{value: 580, name: '邮件营销'},
{value: 484, name: '联盟广告'},
{value: 300, name: '视频广告'}
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
option && myChart.setOption(option);
}
}
}
</script>
<style scoped>
</style>
13.http工具类
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @Package com.cmb.util
* @Description: ${通用HttpClientUtil工具类}
*/
@Slf4j
public class MyHttpClientUtils {
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("Connection", "close");
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
log.error(e.getMessage());
} finally {
try {
httpclient.close();
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
return resultString;
}
public static String doGetWithToken(String url, Map<String, String> param, String token, String tokenName) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET 请求
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader(tokenName, token);
httpGet.setHeader("Connection", "close");
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为 200
if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
log.error(e.getMessage());
} finally {
try {
httpclient.close();
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
return resultString;
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Connection", "close");
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
log.error(e.getMessage());
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
return resultString;
}
public static String doPostOfMultipartFormData(String url, File file, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Connection", "close");
// 创建请求内容
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
if (file != null && file.exists() && file.isFile()) {
multipartEntityBuilder.addBinaryBody("file", file);
}
if (param != null) {
for (String key : param.keySet()) {
multipartEntityBuilder.addTextBody(key, param.get(key));
}
}
httpPost.setEntity(multipartEntityBuilder.build());
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
log.error(e.getMessage());
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
return resultString;
}
/**
* post提交json数据
*
* @param url
* @param json
* @return
*/
public static String doPostOfJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Connection", "close");
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
log.error("【接口调用】HttpClientUtil的doPostOfJson方法报错!错误信息为:{}", e.getMessage());
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error("【接口调用】HttpClientUtil的doPostOfJson方法,关闭资源时报错!错误信息为:{}", e.getMessage());
}
}
return resultString;
}
/**
* post提交json数据 带token
*
* @param url
* @param json
* @param token
* @return
*/
public static String doPostWithTokenOfJson(String url, String json, String token) {
return doPostWithTokenOfJson(url, json, token, "Authorization");
}
/**
* post提交json数据 带token
*
* @param url
* @param json
* @param token
* @return
*/
public static String doPostWithTokenOfJson(String url, String json, String token, String tokenName) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(tokenName, token);
httpPost.setHeader("Connection", "close");
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
log.error("【接口调用】HttpClientUtil的doPostWithTokenOfJson方法报错!错误信息为:{}", e.getMessage());
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error("【接口调用】HttpClientUtil的doPostWithTokenOfJson方法,关闭资源时报错!错误信息为:{}", e.getMessage());
}
}
return resultString;
}
public static String doPutOfJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Put请求
HttpPut httpPut = new HttpPut(url);
httpPut.setHeader("Connection", "close");
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPut.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPut);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
log.error(e.getMessage());
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
return resultString;
}
public static String doDelete(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建Http Delete请求
HttpDelete httpDelete = new HttpDelete(uri);
httpDelete.setHeader("Connection", "close");
// 执行http请求
response = httpClient.execute(httpDelete);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
log.error(e.getMessage());
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
return resultString;
}
public static String doDeleteOfJson(String url, String json) {
/**
* 没有现成的delete可以带json的,自己实现一个,参考HttpPost的实现
*/
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
@SuppressWarnings("unused")
public HttpDeleteWithBody() {
}
@SuppressWarnings("unused")
public HttpDeleteWithBody(URI uri) {
setURI(uri);
}
public HttpDeleteWithBody(String uri) {
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
StringEntity params = new StringEntity(json, ContentType.APPLICATION_JSON);
httpDelete.setEntity(params);
httpDelete.setHeader("Connection", "close");
// 执行http请求
response = httpClient.execute(httpDelete);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
log.error(e.getMessage());
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
return resultString;
}
}
14.页面布局代码
可用于,分块展示各类echarts统计图,监控大屏布局
<template>
<el-scrollbar class="scrollbar">
<div class="app-container">
<div class="top">
<div class="top1">
<div class="top11">
<div class="top111">
</div>
<div class="top112">
</div>
</div>
<div class="top12">
<div class="top121">
</div>
<div class="top122">
</div>
</div>
</div>
<div class="top2">
<div class="top21">
</div>
</div>
<div class="top3">
<div class="top31">
</div>
</div>
</div>
<div class="bottom">
<div class="bottom1">
<div class="bottom11">
</div>
</div>
<div class="bottom2">
<div class="bottom21">
</div>
</div>
</div>
</div>
</el-scrollbar>
</template>
<script>
export default {
name: 'dashboard',
components: {
},
data() {
return {
}
},
created() {
},
methods: {
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.app-container {
margin-top: 2px;
margin-left: 2px;
top: 105px;
left: 24px;
width: 1710px;
height: 880px;
.top {
/*border: 1px solid #e5e5e5;*/
margin-right: -1px;
height: 50%;
position: relative;
width: 100%;
float: top;
white-space: nowrap;
.top1 {
height: 100%;
/*border-right: 1px solid #e5e5e5;*/
width: 540px;
float: left;
.top11 {
/*border-bottom: 1px solid #e5e5e5;*/
height: 47%;
position: relative;
width: 100%;
float: top;
white-space: nowrap;
.top111 {
height: 98%;
width: 45%;
float: left;
background-color: #ffffff
}
.top112 {
height: 98%;
margin-left: 30px;
width: 45%;
float: left;
background-color: #ffffff
}
}
.top12 {
/*border-bottom: 1px solid #e5e5e5;*/
height: 47%;
position: relative;
width: 100%;
float: top;
white-space: nowrap;
.top121 {
height: 98%;
width: 45%;
float: left;
margin-top: 30px;
background-color: #ffffff
}
.top122 {
height: 98%;
margin-top: 30px;
margin-left: 30px;
width: 45%;
float: left;
background-color: #ffffff
}
}
}
.top2 {
height: 100%;
/*border-right: 1px solid #e5e5e5;*/
width: 520px;
float: left;
padding-left: 10px;
.top21 {
height: 100%;
background-color: #ffffff;
}
}
.top3 {
height: 100%;
/*border-right: 1px solid #e5e5e5;*/
width: 592px;
float: left;
padding-left: 30px;
.top31 {
height: 100%;
background-color: #ffffff;
}
}
}
.bottom {
/*border: 1px solid #e5e5e5;*/
margin-right: -1px;
height: 48%;
position: relative;
width: 100%;
float: top;
white-space: nowrap;
.bottom1 {
height: 98%;
/*border-right: 1px solid #e5e5e5;*/
width: 680px;
float: left;
margin-top: 25px;
.bottom11 {
font-size: 23px;
height: 100%;
width: 98%;
background-color: #ffffff;
}
}
.bottom2 {
height: 98%;
/*border-right: 1px solid #e5e5e5;*/
width: 955px;
float: left;
margin-top: 25px;
margin-left: 15px;
.bottom21 {
height: 100%;
width: 100%;
background-color: #ffffff;
}
}
}
}
</style>