郑勇-个人博客 每多学一点知识,就少写一行代码 2020-04-23T04:32:58.324Z https://blog.csdn.net/zhengyong15984285623?viewmode=contents/ 郑勇 Hexo Livy部署及使用文档 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2020/04/23/Livy部署及使用文档/ 2020-04-23T03:04:33.000Z 2020-04-23T04:32:58.324Z 前言
本次部署是在单台机器10.57.17.215上部署,只部署了spark和livy;通过配置livy加载本地文件jar;然后通过livy rest api提交spark任务;

一、前置条件

1.安装spark: (部署参考:https://zyongjava.github.io/2019/12/24/Spark%E9%9B%86%E7%BE%A4%E9%83%A8%E7%BD%B2/)2.安装hadoop(可选,没有使用本地文件测试)

二、安装部署

1)下载安装包

http://livy.incubator.apache.org/download/

2) 创建配置文件livy.conf

1
2
3
cd apache-livy-0.7.0-incubating-bin/conf
cp livy.conf.template livy.conf
vi livy.conf

livy.conf中修改内容如下:

1
2
3
4
5
6
7
8
9
10
# What host address to start the server on. By default, Livy will bind to all network interfaces.
livy.server.host = 10.57.17.215

# What spark master Livy sessions should use.
livy.spark.master = spark://10.57.17.215:7077

# List of local directories from where files are allowed to be added to user sessions. By
# default it's empty, meaning users can only reference remote URIs when starting their
# sessions.
livy.file.local-dir-whitelist = /home/admin/apps/jars/

3) 创建配置文件livy-env.sh

1
2
3
cd apache-livy-0.7.0-incubating-bin/conf
cp livy-env.sh.template livy-env.sh
vi livy-env.sh

livy-env.sh中新增内容如下:

1
2
export SPARK_HOME=/usr/lib/spark
export HADOOP_CONF_DIR=/etc/hadoop/conf

4) 创建配置文件spark-blacklist.conf

1
2
3
cd apache-livy-0.7.0-incubating-bin/conf
cp spark-blacklist.conf.template spark-blacklist.conf
vi spark-blacklist.conf

spark-blacklist.conf中修改内容如下(注释掉下面2行内容),让客户端可以配置这2个参数:

1
2
3
# Disallow overriding the master and the deploy mode.
#spark.master
#spark.submit.deployMode

5)启动程序

1
2
3
cd apache-livy-0.7.0-incubating-bin

./bin/livy-server start

6)验证测试

1
http://10.57.17.215:8998/ui

三、REST调用

API文档地址:http://livy.incubator.apache.org/docs/latest/rest-api.html

1)调用测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* https://www.jianshu.com/p/65d3150e8999
*
* https://blog.csdn.net/qq_36330643/article/details/76686225?locationNum=1&fps=1
*
* Q: requirement failed: Local path /data01/admin/apps/zy/transform/lib/etl.jar cannot be added to user sessions.
*
* A: 修改livy.conf: livy.file.local-dir-whitelist = /data01/admin/jars/
*
* # List of local directories from where files are allowed to be added to user sessions. By
# default it's empty, meaning users can only reference remote URIs when starting their
# sessions.
*
*
* @author: zhengyong Date: 2020/4/17 Time: 9:48 AM
*/
public class LivyTest {

public static void main(String[] args) throws IOException {
String url = "http://10.57.17.215:8998/batches";
List<Integer> sessionIds = getBatches(url);
deleteBatches(url, sessionIds);
String batches = postBatches(url);
}


public static void deleteBatches(String url, List<Integer> sessionIds) throws IOException {
for (Integer id : sessionIds) {
String deleteResult = HttpConfigClient.deleteLivy(String.format("%s/%s", url, id));
System.out.println(String.format("delete batches id=%s, result: %s", id, deleteResult));
}
}


public static List<Integer> getBatches(String url) throws IOException {
String sessions = HttpConfigClient.getLivy(url, null);
JSONObject object = JSON.parseObject(sessions);
JSONArray array = object.getJSONArray("sessions");
if (array == null) {
return null;
}
List<Integer> sessionIds = new ArrayList<>(array.size());
for (Object o : array) {
JSONObject obj = (JSONObject) o;
int id = obj.getIntValue("id");
String name = obj.getString("name");
String state = obj.getString("state");
sessionIds.add(id);
System.out.println(String.format("query session id=%s, name=%s(%s)", id, name, state));
}
return sessionIds;
}

public static String postBatches(String url) throws IOException {
LivyEntity livyEntity = new LivyEntity();
livyEntity.setFile("/home/admin/apps/jars/etl.jar");
livyEntity.setClassName("cn.etl.DataEtlMain");
livyEntity.setNumExecutors(3);
livyEntity.setName("ETL");
livyEntity.setExecutorMemory("4g");
livyEntity.setExecutorCores(2);
livyEntity.setArgs(Lists.newArrayList("params1"));

//spark参数设置: http://spark.apache.org/docs/latest/configuration.html
Map<String, Object> conf = new HashMap<>();
conf.put("spark.master","spark://10.57.17.215:7077");
conf.put("spark.submit.deployMode", "cluster"); // 这一行可以把任务在spark UI上面显示;但是jar包log不能显示
conf.put("spark.driver.cores", "2");
conf.put("spark.driver.memory", "4g");
livyEntity.setConf(conf);

String result = HttpConfigClient.postLivy(url, JSON.toJSONString(livyEntity));
System.out.println("post batches result: " + result);
return result;
}
}

2)httpclient工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

/**
*
*/
public class HttpConfigClient {

public static String postLivy(String postUrl, String json) throws IOException {
CloseableHttpClient livyClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(postUrl);
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
CloseableHttpResponse response = livyClient.execute(httpPost);
return handleResponse(response);
}

public static String getLivy(String getUrl, Map<String, Object> parametersMap) throws IOException {
CloseableHttpClient livyClient = HttpClients.createDefault();
String url = buildUri(getUrl, parametersMap).toString();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = livyClient.execute(httpGet);
return handleResponse(response);
}

public static String deleteLivy(String deleteUrl) throws IOException {
CloseableHttpClient livyClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(deleteUrl);
CloseableHttpResponse response = livyClient.execute(httpDelete);
return handleResponse(response);
}

/***
* 拼接get请求调用的URL
*
* @param url 调用请求
* @param parametersMap 业务数据,作为参数
* @return 完成url
*/
private static URI buildUri(String url, Map<String, Object> parametersMap) {
if (MapUtils.isEmpty(parametersMap)) {
return URI.create(url);
}
ArrayList list = new ArrayList(parametersMap.size());
Iterator iterator = parametersMap.entrySet().iterator();

while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
list.add(entry.getKey().toString().trim() + "=" + entry.getValue().toString().trim());
}
return list.isEmpty() ? URI.create(url) : URI.create(url + "?" + StringUtils.join(list, "&"));
}

/**
* 获取结果
*
* @param response 响应
* @return 返回结果
* @throws IOException
*/
private static String handleResponse(CloseableHttpResponse response) throws IOException {
HttpEntity resultEntity = response.getEntity();
return EntityUtils.toString(resultEntity);
}
}

3)实体对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import java.util.List;
import java.util.Map;

/**
* Livy REST API 封装
* 批处理任务 属性封装
*/
public class LivyEntity {


/**

* 必须有
* 包含需要执行应用的文件,主要是jar包
*/
private String file;
/**
* User to impersonate when running the job
*/
private String proxyUser;
/**
* Application Java/Spark main class
* 主类
*/
private String className;

/**
* Command line arguments for the application
* 参数
*/
private List<String> args;

/**
* jars to be used in this session
* 这个任务里面用到的其他 jar 包
*/
private List<String> jars;

/**
* Python files to be used in this session
*/
private List<String> pyFiles;
/**
* files to be used in this session
*/
private List<String> files;

/**
* Amount of memory to use for the driver process
*/
private String driverMemory;

/**
* Number of cores to use for the driver process
*/
private Integer driverCores;

/**
* Amount of memory to use per executor process
*/
private String executorMemory;
/**
* Number of cores to use for each executor
*/
private Integer executorCores;
/**
* Number of executors to launch for this session
*/
private Integer numExecutors;
/**
* Archives to be used in this session
*/
private List<String> archives;
/**
* The name of the YARN queue to which submitted
*/
private String queue;
/**
* The name of this session
* 任务名称
*/
private String name;
/**
* Spark configuration properties
* spark 配置文件
*/
private Map<String, Object> conf;

public String getFile() {
return file;
}

public void setFile(String file) {
this.file = file;
}

public String getProxyUser() {
return proxyUser;
}

public void setProxyUser(String proxyUser) {
this.proxyUser = proxyUser;
}

public String getClassName() {
return className;
}

public void setClassName(String className) {
this.className = className;
}

public List<String> getArgs() {
return args;
}

public void setArgs(List<String> args) {
this.args = args;
}

public List<String> getJars() {
return jars;
}

public void setJars(List<String> jars) {
this.jars = jars;
}

public List<String> getPyFiles() {
return pyFiles;
}

public void setPyFiles(List<String> pyFiles) {
this.pyFiles = pyFiles;
}

public List<String> getFiles() {
return files;
}

public void setFiles(List<String> files) {
this.files = files;
}

public String getDriverMemory() {
return driverMemory;
}

public void setDriverMemory(String driverMemory) {
this.driverMemory = driverMemory;
}

public Integer getDriverCores() {
return driverCores;
}

public void setDriverCores(Integer driverCores) {
this.driverCores = driverCores;
}

public String getExecutorMemory() {
return executorMemory;
}

public void setExecutorMemory(String executorMemory) {
this.executorMemory = executorMemory;
}

public Integer getExecutorCores() {
return executorCores;
}

public void setExecutorCores(Integer executorCores) {
this.executorCores = executorCores;
}

public Integer getNumExecutors() {
return numExecutors;
}

public void setNumExecutors(Integer numExecutors) {
this.numExecutors = numExecutors;
}

public List<String> getArchives() {
return archives;
}

public void setArchives(List<String> archives) {
this.archives = archives;
}

public String getQueue() {
return queue;
}

public void setQueue(String queue) {
this.queue = queue;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Map<String, Object> getConf() {
return conf;
}

public void setConf(Map<String, Object> conf) {
this.conf = conf;
}

}

四、异常问题

问题:requirement failed: Local path /home/admin/apps/jars/etl.jar cannot be added to user sessions.

解决办法:修改livy.conf配置

1
livy.file.local-dir-whitelist = /home/admin/apps/jars/

五、代码地址

https://github.com/zyongjava/pomelo/tree/master/src/main/java/livy
]]>
<h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><pre><code>本次部署是在单台机器10.57.17.215上部署,只部署了spark和livy;通过配置livy加载本地文件jar;然后通
HIVE部署 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2019/12/24/HIVE部署/ 2019-12-24T03:08:13.000Z 2019-12-24T06:26:08.966Z 前言

部署hive需要提前部署好以下环境:

  1. mysql (安装在10.57.22.113)
  2. HDFS (hadoop-2.7.7)

一、搭建模式

Hive中搭建分如下3中方式,三种方式归根到底就是元数据的存储位置不一样

1
2
3
a)内嵌Derby方式 :运行hive会在当前目录生成一个derby文件和一个metastore_db目录。这种存储方式的弊端是在同一个目录下同时只能有一个hive客户端能使用数据库。
b)mysql Local方式 (hive.metastore.uris为空表示嵌入模式或本地模式)
c)多用户模式 (mysql Remote方式; hive.metastore.uris不为空为远程模式)

二、部署Hive

A)下载地址:https://archive.apache.org/dist/hive/hive-2.3.4/apache-hive-2.3.4-bin.tar.gz

B)解压包:tar -xvf apache-hive-2.3.4-bin.tar.gz

C)修改文件夹名称:mv apache-hive-2.3.4-bin hive-2.3.4

D)配置环境变量, 修改.bashrc文件

vi ~/.bashrc

1
2
export HIVE_HOME=/data01/bigdata/hive-2.3.4
export PATH=$PATH:$HIVE_HOME/bin

source ~/.bashrc

三、配置修改

A)修改hive-site.xml配置

首先复制一份配置文件cp hive-default.xml.template hive-site.xml,修改如下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<!-- 指定HDFS中的hive仓库地址 --> 
<property>
<name>hive.metastore.warehouse.dir</name>
<value>/data01/bigdata/hive-2.3.4/warehouse</value>
<description>location of default database for the warehouse</description>
</property>

<property>
<name>hive.exec.scratchdir</name>
<value>/data01/bigdata/hive-2.3.4</value>
<description>HDFS root scratch dir for Hive jobs which gets created with write all (733) permission. For each connecting user, an HDFS scratch dir: ${hive.exec.scratchdir}/&lt;username&gt; is created, with ${hive.scratch.dir.permission}.</description>
</property>

<!-- 指定驱动类 -->
<property>
<name>javax.jdo.option.ConnectionDriverName</name>
<value>com.mysql.jdbc.Driver</value>
<description>Driver class name for a JDBC metastore</description>
</property>

<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:mysql://10.57.22.113/hive_remote?createDatabaseIfNotExist=true</value>
<description>
JDBC connect string for a JDBC metastore.
To use SSL to encrypt/authenticate the connection, provide database-specific SSL flag in the connection URL.
For example, jdbc:postgresql://myhost/db?ssl=true for postgres database.
</description>

<property>
<name>javax.jdo.option.ConnectionUserName</name>
<value>root</value>
<description>Username to use against metastore database</description>
</property>

<property>
<name>javax.jdo.option.ConnectionPassword</name>
<value>root</value>
<description>password to use against metastore database</description>
</property>

<!-- 该属性为空表示嵌入模式或本地模式,否则为远程模式 -->
<property>
<name>hive.metastore.uris</name>
<value>thrift://10.57.22.119:9083</value>
<description>Thrift URI for the remote metastore. Used by metastore client to connect to remote metastore.</description>
</property>

<property>
<name>hive.exec.local.scratchdir</name>
<value>/tmp/hive/local</value>
<description>Local scratch space for Hive jobs</description>
</property>

<property>
<name>hive.downloaded.resources.dir</name>
<value>/tmp/hive/resources</value>
<description>Temporary local directory for added resources in the remote file system.</description>
</property>

<property>
<name>hive.server2.webui.host</name>
<value>tdcdh119</value>
<description>The host address the HiveServer2 WebUI will listen on</description>
</property>
<property>
<name>hive.server2.webui.port</name>
<value>10002</value>
<description>The port the HiveServer2 WebUI will listen on. This can beset to 0 or a negative integer to disable the web UI</description>
</property>

B) 修改hive-env.sh变量

首先复制一份配置文件cp hive-env.sh.template hive-env.sh, 新增如下配置:

1
2
3
export  HADOOP_HOME=/data01/bigdata/hive-2.3.4
export HIVE_CONF_DIR=/data01/bigdata/hive-2.3.4/conf
export HIVE_AUX_JARS_PATH=/data01/bigdata/hive-2.3.4lib

四、其他配置

A) 新建warehouse目录

1
2
3
4
5
mkdir /data01/bigdata/hive-2.3.4/warehouse

将warehouse变为hadoop仓库
hadoop fs -mkdir -p /data01/bigdata/hive-2.3.4/warehouse
hadoop fs -chmod 777 /data01/bigdata/hive-2.3.4/warehouse

B)上传mysql-connector-java-5.1.40.jar到指定目录$HADOOP_HOME/lib

1
scp ~/Downloads/mysql-connector-java-5.1.40.jar admin@10.57.22.119:/data01/bigdata/hive-2.3.4/lib

C) 创建存储元数据的mysql库

1
2
mysql -h 10.57.22.113 -u root -p
create database hive_remote;

D) 初始化schema(/data01/bigdata/hive-2.3.4/bin/schematool)

1
schematool -dbType mysql -initSchema

进入mysql查看初始化schema后结果,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
mysql> use hive_remote;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+---------------------------+
| Tables_in_hive_remote |
+---------------------------+
| aux_table |
| bucketing_cols |
| cds |
| columns_v2 |
| compaction_queue |
| completed_compactions |
| completed_txn_components |
| database_params |
| db_privs |
| dbs |
| delegation_tokens |
| func_ru |
| funcs |
| global_privs |
| hive_locks |
| idxs |
| index_params |
| key_constraints |
| master_keys |
| next_compaction_queue_id |
| next_lock_id |
| next_txn_id |
| notification_log |
| notification_sequence |
| nucleus_tables |
| part_col_privs |
| part_col_stats |
| part_privs |
| partition_events |
| partition_key_vals |
| partition_keys |
| partition_params |
| partitions |
| role_map |
| roles |
| sd_params |
| sds |
| sequence_table |
| serde_params |
| serdes |
| skewed_col_names |
| skewed_col_value_loc_map |
| skewed_string_list |
| skewed_string_list_values |
| skewed_values |
| sort_cols |
| tab_col_stats |
| table_params |
| tbl_col_privs |
| tbl_privs |
| tbls |
| txn_components |
| txns |
| type_fields |
| types |
| version |
| write_set |
+---------------------------+
57 rows in set (0.06 sec)

五、启动hive server

1
2
3
4
5
启动 hive server
nohup hive --service metastore &

启动hive web UI
nohup hive --service hiveserver2 &

进程查看,是否有RunJar进程(有即服务已启动):

1
2
3
[admin@tdcdh119 warehouse]$ jps
17627 RunJar
19643 Jps

六、启动hive client

1
hive

验证hive

1
2
3
4
5
6
7
8
hive> create databases hive_test;
OK
Time taken: 1.184 seconds
hive> show databases;
OK
default
hive_test
Time taken: 1.131 seconds, Fetched: 2 row(s)

七、参考文档

1
2
3
4
5
6
7
8
9
https://cwiki.apache.org/confluence/display/Hive/GettingStarted#GettingStarted-InstallingHivefromaStableRelease

https://www.cnblogs.com/LHWorldBlog/p/8289702.html

https://www.cnblogs.com/dxxblog/p/8193967.html

https://www.cnblogs.com/xuwujing/p/8045821.html

https://blog.csdn.net/zhangxiaohui4445/article/details/90675445
]]>
<h4 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h4><p>部署hive需要提前部署好以下环境:</p> <ol> <li>mysql (安装在10.57.22.113)</li> <li>HDFS
Spark集群部署 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2019/12/24/Spark集群部署/ 2019-12-24T03:05:54.000Z 2019-12-24T03:31:54.591Z 前言

本次基于Standalone的Spark集群部署使用3台服务器,分布如下:

服务器地址hostnameMasterWorker
10.57.22.116tdcdh116noyes
10.57.22.117tdcdh117noyes
10.57.22.119tdcdh119yesyes

一、部署

下载地址:https://archive.apache.org/dist/spark/spark-2.3.4/

A. 解压安装包

1
tar -xvf spark-2.3.4-bin-hadoop2.7.tgz

B. 更改包名称为spark-2.3.4

1
mv spark-2.3.4-bin-hadoop2.7/spark-2.3.4

C. 配置slaves(即Worker主机)

1)进入包目录:/data01/bigdata/spark-2.3.4/conf

2) 复制文件:cp slaves.template slaves

3) 修改文件:vi slaves

1
2
3
tdcdh116
tdcdh117
tdcdh119

D. 配置spark-env.sh

1)新建work目录:mkdir /data01/bigdata/spark-2.3.4/work

2) 复制文件:cp spark-env.template spark-env.sh

3) 修改文件:vi spark-env.sh

新增如下配置:

1
2
3
4
5
6
7
8
9
10
11
#主节点ip或hostname
export SPARK_MASTER_HOST=tdcdh119
#主节点的端口
export SPARK_MASTER_PORT=7077
#worker的工作目录区
export SPARK_WORKER_DIR=/data01/bigdata/spark-2.3.4/work
export SPARK_WORKER_MEMORY=1g
export SPARK_WORKER_CORES=2
export JAVA_HOME=/data01/admin/local/jdk8u191
export HADOOP_HOME=/data01/bigdata/hadoop-2.7.7
export HADOOP_CONF_DIR=/data01/bigdata/hadoop-2.7.7/etc/hadoop

E. 将包拷贝到所有机器

1
2
scp -r spark-2.3.4 admin@10.57.22.116:/data01/bigdata/
scp -r spark-2.3.4 admin@10.57.22.117:/data01/bigdata/

F. 环境变量配置

1) 修改sudo vi ~/.bashrc

1
2
export SPARK_HOME=/data01/bigdata/spark-2.3.4
export PATH=$SPARK_HOME/bin:$SPARK_HOME/sbin:$PATH

2)生效:source ~/.bashrc

G. 启动项目

只需要在Master(10.57.22.119)节点启动即可

1
2
cd /data01/bigdata/spark-2.3.4
sbin/start-all.sh

二、项目验证

http://10.57.22.119:8080/

三、参考文档

https://blog.csdn.net/qq_42825815/article/details/84071702
https://www.cnblogs.com/lyy-blog/p/9636070.html

四、备注

需要免密登录, 参考《HDFS集群部署》

]]>
<h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>本次基于Standalone的Spark集群部署使用3台服务器,分布如下:</p> <table> <thead> <tr> <th>服务器
HDFS集群部署 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2019/12/24/HDFS集群部署/ 2019-12-24T03:04:37.000Z 2019-12-24T03:31:48.732Z 前言

本次部署使用3台服务器,分布如下:

服务器地址hostnameNameNodeDataNode
10.57.22.116tdcdh116noyes
10.57.22.117tdcdh117noyes
10.57.22.119tdcdh119yesyes

下载地址: https://archive.apache.org/dist/hadoop/common/hadoop-2.7.7/

一、同步服务器时间

1
2
3
4
5
6
7
8
9
10
11
因为安装centos镜像时的选项不同,可能会导致我们各个节点的系统时间不一致,这会导致接收到的信息因为时间相差过大而被认为是过时信息。为了同步各个节点之间的时间,我们借用ntp工具

sudo yum install ntp

然后我们可以去往上搜索那些开放的时间服务器,这里我们采用阿里云的时间服务器

sudo ntpdate ntp1.aliyun.com

同步完成后我们可以在终端打印时间信息

date

二、修改hostname

1) 修改主机名

1
sudo hostname tdcdh119

2) 修改hosts

1
2
3
4
5
6
7
sudo vi /etc/hosts

10.57.22.116 tdcdh116
10.57.22.117 tdcdh117
10.57.22.119 tdcdh119

source /etc/hosts

3) 关闭防火墙

1
sudo systemctl stop firewalld

三、配置免密登录

a. 查看本地是否有秘钥:执行命令ls ~/.ssh查看是否有文件id_rsa和id_rsa.pub

b. 生成秘钥:如果没有看到a步骤中的两个文件则执行下面命令生成公钥和私钥ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa

c. 免密设置:第a,b步是在所有节点执行,当前步骤只在主节点(本文档为10.57.22.119节点)执行如下命令:

1
2
3
ssh-copy-id -i ~/.ssh/id_rsa.pub admin@tdcdh116
ssh-copy-id -i ~/.ssh/id_rsa.pub admin@tdcdh117
ssh-copy-id -i ~/.ssh/id_rsa.pub admin@tdcdh119

d. 验证免密是否配置成功: 在10.57.22.116机器上执行命令ssh admin@tdcdh119, 如果不需要密码就能登录证明成功;

四、安装Hadoop

A). 创建数据目录和临时目录:

1
2
3
cd hadoop-2.7.7

mkdir datas tmp datas/data datas/name

B). 配置JAVA_HOME

vi /hadoop-2.7.7/etc/hadoop/hadoop-env.sh

1
export JAVA_HOME=/data01/admin/local/jdk8u191

C). 修改配置文件

1) hdfs-site.xml

10.57.22.116配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<property>
<name>dfs.replication</name>
<value>2</value>
</property>

<property>
<name>dfs.namenode.secondary.http-address</name>
<value>tdcdh116:50090</value>
</property>

<property>
<name>dfs.datanode.data.dir</name>
<value>/data01/bigdata/hadoop-2.7.7/datas/data</value>
</property>

10.57.22.117配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<property>
<name>dfs.replication</name>
<value>2</value>
</property>

<property>
<name>dfs.namenode.secondary.http-address</name>
<value>tdcdh116:50090</value>
</property>

<property>
<name>dfs.datanode.data.dir</name>
<value>/data01/bigdata/hadoop-2.7.7/datas/data</value>
</property>

10.57.22.119配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<property>
<name>dfs.replication</name>
<value>2</value>
</property>

<!-- second namenode节点 -->
<property>
<name>dfs.namenode.secondary.http-address</name>
<value>tdcdh116:50090</value>
</property>

<!-- namenode节点 -->
<property>
<name>dfs.namenode.name.dir</name>
<value>/data01/bigdata/hadoop-2.7.7/datas/name</value>
</property>

<!-- datanode节点 -->
<property>
<name>dfs.datanode.data.dir</name>
<value>/data01/bigdata/hadoop-2.7.7/datas/data</value>
</property>

<!-- 开启webhdfs -->
<property>
<name>dfs.webhdfs.enabled</name>
<value>true</value>
</property>

2)core-site.xml

10.57.22.116、10.57.22.117、10.57.22.119配置均如下:

1
2
3
4
5
6
7
8
9
10
<!-- 指向namenode节点 -->
<property>
<name>fs.defaultFS</name>
<value>hdfs://tdcdh119:9000</value>
</property>

<property>
<name>hadoop.tmp.dir</name>
<value>/data01/bigdata/hadoop-2.7.7/tmp</value>
</property>

3) 修改slaves(即datanode节点)

1
2
3
tdcdh116
tdcdh117
tdcdh119

D)第一次启动前格式化namenode

1
2
3
cd /hadoop-2.7.7

bin/hdfs namenode -format

E)只需要在10.57.22.119节点启动就启动了整个集群(即就把其他2台全部启动了):

1
2
3
cd /hadoop-2.7.7

sbin/start-dfs.sh

五、环境变量配置

1) 修改sudo vi ~/.bashrc

1
2
export HADOOP_HOME=/data01/bigdata/hadoop-2.7.7
export PATH=${HADOOP_HOME}/bin:${HADOOP_HOME}/sbin:$PATH

2)生效:source ~/.bashrc

六、访问地址

http://10.57.22.119:50070/

七、参考文档

https://blog.csdn.net/qq_40246546/article/details/83003389

]]>
<h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>本次部署使用3台服务器,分布如下:</p> <table> <thead> <tr> <th>服务器地址</th> <th>hostname
经典技术文章概览 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/12/28/经典技术文章概览/ 2018-12-28T07:34:58.000Z 2020-10-12T06:41:41.214Z 以下是我平时阅读发现比较有深度的文章;做个记录

文章标题地址
RPC原理http://www.cnblogs.com/LBSer/p/4853234.html
NIO理解http://www.cnblogs.com/LBSer/p/4622749.html
Netty系列之Netty高性能之道http://www.infoq.com/cn/articles/netty-high-performance
自顶向下深入分析Nettyhttps://www.jianshu.com/p/da4398743b5a
https://www.jianshu.com/p/92c5092c5d3f
分布式系统数据一致性http://chuansong.me/n/286764951149
Java 并发开发,内置锁 Synchronizedhttp://www.kuqin.com/shuoit/20170217/353325.html?url_type=39&object_type=webpage&pos=1
Mysql聚簇索引和非聚簇索引原理http://blog.csdn.net/lisuyibmd/article/details/53004848
大顶堆排序http://m.blog.csdn.net/article/details?id=19039931
Junit mockito 解耦合测试https://mp.weixin.qq.com/s?__biz=MjM5NzMyMjAwMA==&mid=2651478581&idx=2&sn=0b40e885c2fb81be865a2f7567713a3f&chksm=bd25364a8a52bf5c6fc2f13af0429f8e07b60a47a07e95a657e1339aac229ae4ab5a3f54b059&mpshare=1&scene=1&srcid=05249JIFI9paA3zVLBVrqi9g#rd
Dubbo中消费者初始化的过程解析http://cxis.me/2017/03/21/Dubbo%E4%B8%AD%E6%B6%88%E8%B4%B9%E8%80%85%E5%88%9D%E5%A7%8B%E5%8C%96%E7%9A%84%E8%BF%87%E7%A8%8B%E8%A7%A3%E6%9E%90/?utm_source=tuicool&utm_medium=referral
海量数据处理算法—Bloom Filterhttp://blog.csdn.net/hguisu/article/details/7866173
Kafka剖析(一):Kafka背景及架构介绍http://www.infoq.com/cn/articles/kafka-analysis-part-1
一个java对象到底内存有多大http://www.cnblogs.com/zhanjindong/p/3757767.html
关于分布式事务、两阶段提交协议、三阶提交协议http://blog.jobbole.com/95632
java知识分享https://github.com/crossoverJie/Java-Interview
spring集成mybatis实现mysql读写分离https://www.cnblogs.com/lidj/p/7337535.html
DDD-领域驱动设计在互联网业务开发中的实践https://zhuanlan.zhihu.com/p/32459776
注释驱动的 Spring cache 缓存介绍https://www.ibm.com/developerworks/cn/opensource/os-cn-spring-cache/index.html
Tomcat系统架构https://blog.csdn.net/xlgen157387/article/details/79006434
Tomcat工作原理https://www.ibm.com/developerworks/cn/java/j-lo-tomcat1
图解Tomcat类加载机制https://www.aliyun.com/jiaocheng/290132.html
深入理解Java类加载器(ClassLoader)https://blog.csdn.net/javazejian/article/details/73413292
https原理通俗了解https://www.cnblogs.com/zhangshitong/p/6478721.html
Kafka 的这些原理你知道吗https://segmentfault.com/a/1190000021370626
Flink基础知识详解http://www.54tianzhisheng.cn/tags/Flink/
Dubbo常见面试题https://segmentfault.com/a/1190000037434049
敖丙:知识总结https://segmentfault.com/u/aobing/articles?page=1
]]>
<p>以下是我平时阅读发现比较有深度的文章;做个记录</p> <table> <thead> <tr> <th>文章标题</th> <th>地址</th> </tr> </thead> <tbody> <tr> <td>RPC原理</td> <td><a href="http:/
Java垃圾收集器 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/12/07/Java垃圾收集器/ 2018-12-07T07:24:16.000Z 2018-12-07T07:28:03.500Z GC的分类

GC的主要回收区域就是年轻代(young gen)、老年代(tenured gen)、持久区(perm gen),在jdk8之后,perm gen消失,被替换成了元空间(Metaspace),元空间会在普通的堆区进行分配。垃圾收集为了提高效率,采用分代收集的方式,对于不同特点的回收区域使用不同的垃圾收集器。系统正常运行情况young是比较频繁的,full gc会触发整个heap的扫描和回收。在G1垃圾收集器中,最好的优化状态就是通过不断调整分区空间,避免进行full gc,可以大幅提高吞吐量。下面会详细介绍。

串行垃圾回收器

单线程回收,并且会有stop theworld(下文会简称STW),也即GC时,暂停所有用户线程。其运行方式是单线程的,适合Client模式的应用,适合单CPU环境。串行的垃圾收集器有两种,Serial以及SerialOld,一般会搭配使用。新生代使用Serial采取复制算法,老年代使用Serial Old采取标记整理算法。Client应用或者命令行程序可以,通过-XX:+UseSerialGC可以开启上述回收模式。

Serial:用于新生代垃圾收集 (复制算法)

SerialOld:用于老年代垃圾收集 (标记整理算法)

并行垃圾回收器

整体来说,并行垃圾回收相对于串行,是通过多线程运行垃圾收集的。也会stop-the-world。适合Server模式以及多CPU环境。一般会和jdk1.5之后出现的CMS搭配使用。并行的垃圾回收器有以下几种:

ParNew:Serial收集器的多线程版本,默认开启的收集线程数和cpu数量一样,运行数量可以通过修改ParallelGCThreads设定。用于新生代收集,使用-XX:+UseParNewGC,和Serial Old收集器组合进行内存回收。(复制算法)

Parallel Scavenge: 关注吞吐量,吞吐量优先,吞吐量=代码运行时间/(代码运行时间+垃圾收集时间),也就是高效率利用cpu时间,尽快完成程序的运算任务
可以设置最大停顿时间MaxGCPauseMillis以及,吞吐量大小GCTimeRatio。如果设置了-XX:+UseAdaptiveSizePolicy参数,则随着GC,会动态调整新生代的大小,Eden,Survivor比例等,以提供最合适的停顿时间或者最大的吞吐量。用于新生代收集。通过-XX:+UseParallelGC参数,Server模式下默认提供了其和SerialOld进行搭配的分代收集方式 (复制算法)

Parllel Old:Parallel Scavenge的老年代版本。JDK 1.6开始提供的。在此之前Parallel Scavenge的地位也很尴尬,而有了Parllel Old之后,通过-XX:+UseParallelOldGC参数使用Parallel Scavenge + Parallel Old器组合进行内存回收。

并发标记扫描垃圾回收器(CMS)

CMS(Concurrent Mark Sweep)基于"标记—清除"算法,用于老年代,所以其关注点在于减少“pause time”也即因垃圾回收导致的stop the world时间。对于重视服务的响应速度的应用可以使用CMS。因为CMS是“并发”运行的,也即垃圾收集线程可以和用户线程同时运行。 缺点就是会产生内存碎片。 -XX:UseConcMarkSweepGC参数可以开启CMS,年轻代使用ParNew,老年代使用CMS,同时Serial Old收集器将作为CMS收集器出现Concurrent Mode Failure失败后的后备收集器使用。
CMS的回收分为几个阶段:

初始标记:标记一下GC Roots能直接关联到的对象,会“Stop The World”

并发标记:GC Roots Tracing,可以和用户线程并发执行。

重新标记:标记期间产生的对象存活的再次判断,修正对这些对象的标记,执行时间相对并发标记短,会“Stop The World”。

并发清除:清除对象,可以和用户线程并发执行。

G1垃圾收集器

G1垃圾收集器也是以关注延迟为目标、服务器端应用的垃圾收集器,被HotSpot团队寄予取代CMS的使命,也是一个非常具有调优潜力的垃圾收集器。虽然G1也有类似CMS的收集动作:初始标记、并发标记、重新标记、清除、转移回收,并且也以一个串行收集器做担保机制,但单纯地以类似前三种的过程描述显得并不是很妥当。事实上,G1收集与以上三组收集器有很大不同:

  1. G1的设计原则是”首先收集尽可能多的垃圾(Garbage First)”。因此,G1并不会等内存耗尽(串行、并行)或者快耗尽(CMS)的时候开始垃圾收集,而是在内部采用了启发式算法,在老年代找出具有高收集收益的分区进行收集。同时G1可以根据用户设置的暂停时间目标自动调整年轻代和总堆大小,暂停目标越短年轻代空间越小、总空间就越大;
  2. G1采用内存分区(Region)的思路,将内存划分为一个个相等大小的内存分区,回收时则以分区为单位进行回收,存活的对象复制到另一个空闲分区中。由于都是以相等大小的分区为单位进行操作,因此G1天然就是一种压缩方案(局部压缩);
  3. G1虽然也是分代收集器,但整个内存分区不存在物理上的年轻代与老年代的区别,也不需要完全独立的survivor(to space)堆做复制准备。G1只有逻辑上的分代概念,或者说每个分区都可能随G1的运行在不同代之间前后切换;
  4. G1的收集都是STW的,但年轻代和老年代的收集界限比较模糊,采用了混合(mixed)收集的方式。即每次收集既可能只收集年轻代分区(年轻代收集),也可能在收集年轻代的同时,包含部分老年代分区(混合收集),这样即使堆

总结

Serial收集器(复制算法):新生代单线程收集器,标记和清理都是单线程,优点是简单高效。是client级别默认的GC方式,可以通过-XX:+UseSerialGC来强制指定。

Serial Old收集器(标记-整理算法):老年代单线程收集器,Serial收集器的老年代版本。

ParNew收集器(停止-复制算法):新生代收集器,可以认为是Serial收集器的多线程版本,在多核CPU环境下有着比Serial更好的表现。

Parallel Scavenge收集器(停止-复制算法):并行收集器,追求高吞吐量,高效利用CPU。吞吐量一般为99%, 吞吐量= 用户线程时间/(用户线程时间+GC线程时间)。适合后台应用等对交互相应要求不高的场景。是server级别默认采用的GC方式,可用-XX:+UseParallelGC来强制指定,用-XX:ParallelGCThreads=4来指定线程数。

Parallel Old收集器(停止-复制算法):Parallel Scavenge收集器的老年代版本,并行收集器,吞吐量优先。

CMS(Concurrent Mark Sweep)收集器(标记-清理算法):高并发、低停顿,追求最短GC回收停顿时间,cpu占用比较高,响应时间快,停顿时间短,多核cpu 追求高响应时间的选择。

G1可以根据用户设置的暂停时间目标自动调整年轻代和总堆大小,暂停目标越短年轻代空间越小、总空间就越大;当JVM分配对象到Eden区域失败(Eden区已满)时,触发young gc;年轻代收集不断活动后,老年代的空间也会被逐渐填充。当老年代占用空间超过整堆比IHOP阈值-XX:InitiatingHeapOccupancyPercent(默认45%)时,G1就会启动一次混合垃圾收集()周期

知乎看法一:
1
2
3
4
5
6
7
8
9
10
11
12
13
针对HotSpot VM的实现,它里面的GC其实准确分类只有两大种:
Partial GC:并不收集整个GC堆的模式
Young GC:只收集young gen的GC
Old GC:只收集old gen的GC。只有CMS的concurrentcollection是这个模式
Mixed GC:收集整个young gen以及部分old gen的GC。只有G1有这个模式
Full GC:收集整个堆,包括young gen、old gen、perm gen(如果存在的话)等所有部分的模式。
Major GC通常是跟full GC是等价的,收集整个GC堆。但因为HotSpot VM发展了这么多年,外界对各种名词的解读已经完全混乱了,当有人说“major GC”的时候一定要问清楚他想要指的是上面的full GC还是old GC。

最简单的分代式GC策略,按HotSpot VM的serial GC的实现来看,触发条件是:
young GC:当young gen中的eden区分配满的时候触发。注意young GC中有部分存活对象会晋升到old gen,所以young GC后old gen的占用量通常会有所升高。
full GC:当准备要触发一次young GC时,如果发现统计数据说之前young GC的平均晋升大小比目前old gen剩余的空间大,则不会触发young GC而是转为触发full GC(因为HotSpot VM的GC里,除了CMS的concurrent collection之外,其它能收集old gen的GC都会同时收集整个GC堆,包括young gen,所以不需要事先触发一次单独的young GC);或者,如果有perm gen的话,要在perm gen分配空间但已经没有足够空间时,也要触发一次full GC;或者System.gc()、heap dump带GC,默认也是触发full GC。

HotSpot VM里其它非并发GC的触发条件复杂一些,不过大致的原理与上面说的其实一样。当然也总有例外。Parallel Scavenge(-XX:+UseParallelGC)框架下,默认是在要触发full GC前先执行一次young GC,并且两次GC之间能让应用程序稍微运行一小下,以期降低full GC的暂停时间(因为young GC会尽量清理了young gen的死对象,减少了full GC的工作量)。控制这个行为的VM参数是-XX:+ScavengeBeforeFullGC。这是HotSpot VM里的奇葩嗯。可跳传送门围观:JVM full GC的奇怪现象,求解惑? - RednaxelaFX 的回答并发GC的触发条件就不太一样。以CMS GC为例,它主要是定时去检查old gen的使用量,当使用量超过了触发比例就会启动一次CMS GC,对old gen做并发收集。
知乎看法二:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1. Full GC定义是相对明确的,就是针对整个新生代、老生代、元空间(metaspace,java8以上版本取代perm gen)的全局范围的GC;
2. Minor GC和Major GC是俗称,在Hotspot JVM实现的Serial GC, Parallel GC, CMS, G1 GC中大致可以对应到某个Young GC和Old GC算法组合;
3. 最重要是搞明白上述Hotspot JVM实现中几种GC算法组合到底包含了什么。
3.1 Serial GC算法:Serial Young GC + Serial Old GC (敲黑板!敲黑板!敲黑板!实际上它是全局范围的Full GC);
3.2 Parallel GC算法:Parallel Young GC + 非并行的PS MarkSweep GC / 并行的Parallel Old GC(敲黑板!敲黑板!敲黑板!这俩实际上也是全局范围的Full GC),选PS MarkSweep GC 还是 Parallel Old GC 由参数UseParallelOldGC来控制;
3.3 CMS算法:ParNew(Young)GC + CMS(Old)GC (piggyback on ParNew的结果/老生代存活下来的object只做记录,不做compaction)+ Full GC for CMS算法(应对核心的CMS GC某些时候的不赶趟,开销很大);
3.4 G1 GC:Young GC + mixed GC(新生代,再加上部分老生代)+ Full GC for G1 GC算法(应对G1 GC算法某些时候的不赶趟,开销很大);
4. 搞清楚了上面这些组合,我们再来看看各类GC算法的触发条件。简单说,触发条件就是某GC算法对应区域满了,或是预测快满了。比如,
4.1 各种Young GC的触发原因都是eden区满了;
4.2 Serial Old GC/PS MarkSweep GC/Parallel Old GC的触发则是在要执行Young GC时候预测其promote的object的总size超过老生代剩余size;
4.3 CMS GC的initial marking的触发条件是老生代使用比率超过某值;
4.4 G1 GC的initial marking的触发条件是Heap使用比率超过某值,跟4.3 heuristics 类似;
4.5 Full GC for CMS算法和Full GC for G1 GC算法的触发原因很明显,就是4.3 和 4.4 的fancy算法不赶趟了,只能全局范围大搞一次GC了(相信我,这很慢!这很慢!这很慢!);
5 题主说的 “Full GC会先触发一次Minor GC” - 指的应该是
5.1 PS MarkSweep GC/Parallel Old GC(Full GC)之前会跑一次Parallel Young GC;
原因就是减轻Full GC 的负担。
哇~整个picture 是有点乱,希望我整理的还算清楚

参考文章

垃圾回收器说明:https://blog.csdn.net/lijingyao8206/article/details/80513383

垃圾回收算法说明:https://www.cnblogs.com/1024Community/p/honery.html

知乎大神看法:https://www.zhihu.com/question/41922036/answer/93079526

]]>
<h3 id="GC的分类"><a href="#GC的分类" class="headerlink" title="GC的分类"></a>GC的分类</h3><blockquote> <p>GC的主要回收区域就是年轻代(young gen)、老年代(tenured gen)、持久
JVM性能查看分析 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/12/04/JVM性能查看分析/ 2018-12-04T09:07:37.000Z 2018-12-04T10:19:05.299Z 一、uptime

查看系统负载

1
2
[admin@10-57-19-253 ~]$ uptime
16:34:16 up 36 days, 5:49, 1 user, load average: 0.00, 0.01, 0.05

解析:

1
2
3
4
16:34:16    //当前系统时间
up 1 day, 5:49 //持续运行时间,时间越大,说明你的机器越稳定。
1 users //用户连接数,是总连接数而不是用户数
average: 0.00, 0.01, 0.05 //系统平均负载,统计最近1,5,15分钟的系统平均负载

二、top

查看系统PID、进程占用CPU、内存、用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
top - 16:31:40 up 36 days,  5:47,  1 user,  load average: 0.00, 0.01, 0.05
Tasks: 112 total, 1 running, 111 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.0 us, 0.1 sy, 0.0 ni, 99.9 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 8010176 total, 6052396 free, 1054808 used, 902972 buff/cache
KiB Swap: 0 total, 0 free, 0 used. 6621668 avail Mem

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
291 root 20 0 0 0 0 S 0.3 0.0 9:19.76 xfsaild/vda2
18591 admin 20 0 5069284 871172 13056 S 0.3 10.9 214:37.38 java
1 root 20 0 128168 6744 3984 S 0.0 0.1 1:00.66 systemd
2 root 20 0 0 0 0 S 0.0 0.0 0:00.74 kthreadd
3 root 20 0 0 0 0 S 0.0 0.0 0:00.12 ksoftirqd/0
5 root 0 -20 0 0 0 S 0.0 0.0 0:00.00 kworker/0:0H
6 root 20 0 0 0 0 S 0.0 0.0 0:00.00 kworker/u8:0
7 root rt 0 0 0 0 S 0.0 0.0 0:00.48 migration/0
8 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcu_bh
9 root 20 0 0 0 0 S 0.0 0.0 2:37.71 rcu_sched
10 root rt 0 0 0 0 S 0.0 0.0 0:09.80 watchdog/0
11 root rt 0 0 0 0 S 0.0 0.0 0:08.44 watchdog/1
12 root rt 0 0 0 0 S 0.0 0.0 0:00.34 migration/1
13 root 20 0 0 0 0 S 0.0 0.0 0:01.15 ksoftirqd/1
15 root 0 -20 0 0 0 S 0.0 0.0 0:00.00 kworker/1:0H
16 root rt 0 0 0 0 S 0.0 0.0 0:08.99 watchdog/2
17 root rt 0 0 0 0 S 0.0 0.0 0:00.52 migration/2
18 root 20 0 0 0 0 S 0.0 0.0 0:00.13 ksoftirqd/2

可知java进程PID为18591.

top -p PID

查看指定java进程的CPU/内存使用情况。

1
2
3
4
5
6
7
8
9
[admin@10-57-19-253 ~]$ top -p 18591
top - 16:35:58 up 36 days, 5:51, 1 user, load average: 0.00, 0.01, 0.05
Tasks: 1 total, 0 running, 1 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 8010176 total, 6042444 free, 1055312 used, 912420 buff/cache
KiB Swap: 0 total, 0 free, 0 used. 6621028 avail Mem

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
18591 admin 20 0 5069284 871172 13056 S 0.0 10.9 214:38.43 java
top -Hp PID

根据进程查找内部线程内存和CPU使用情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
admin@10-57-19-253 ~]$ top -Hp 18591
top - 16:53:32 up 36 days, 6:09, 1 user, load average: 0.00, 0.01, 0.05
Threads: 334 total, 0 running, 334 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.1 us, 0.0 sy, 0.0 ni, 99.9 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 8010176 total, 5946812 free, 1051908 used, 1011456 buff/cache
KiB Swap: 0 total, 0 free, 0 used. 6622372 avail Mem

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
18677 admin 20 0 5069284 875844 13088 S 0.3 10.9 56:00.08 java
18591 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:00.00 java
18592 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:00.58 java
18593 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:02.83 java
18594 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:02.89 java
18595 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:02.95 java
18596 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:02.98 java
18597 admin 20 0 5069284 875844 13088 S 0.0 10.9 2:55.02 java
18598 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:00.25 java
18599 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:00.25 java
18600 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:00.00 java
18601 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:00.00 java
18602 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:00.00 java
18603 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:55.14 java
18604 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:51.45 java
18605 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:22.95 java
18606 admin 20 0 5069284 875844 13088 S 0.0 10.9 0:00.00 java
18607 admin 20 0 5069284 875844 13088 S 0.0 10.9 19:09.66 java

三、jps

查看java进程PID

1
2
3
[admin@10-57-19-253 ~]$ jps
26668 Jps
18591 Bootstrap

四、jstat

用于输出java程序内存使用情况,包括新生代、老年代、元数据区容量、垃圾回收情况; 命令jstat -gcutil PID interval count:表示没1000毫秒统计一次结果,共5次

1
2
3
4
5
6
7
[admin@10-57-19-253 ~]$ jstat -gcutil 18591 1000 5
S0 S1 E O M CCS YGC YGCT FGC FGCT GCT
0.00 67.17 27.74 17.08 97.29 94.54 1201 6.722 3 0.280 7.003
0.00 67.17 27.74 17.08 97.29 94.54 1201 6.722 3 0.280 7.003
0.00 67.17 27.74 17.08 97.29 94.54 1201 6.722 3 0.280 7.003
0.00 67.17 28.55 17.08 97.29 94.54 1201 6.722 3 0.280 7.003
0.00 67.17 28.55 17.08 97.29 94.54 1201 6.722 3 0.280 7.003
1
2
3
4
5
6
7
8
9
10
S0:幸存1区当前使用比例
S1:幸存2区当前使用比例
E:伊甸园区使用比例
O:老年代使用比例
M:元数据区使用比例
CCS:压缩使用比例
YGC:年轻代垃圾回收次数
FGC:老年代垃圾回收次数
FGCT:老年代垃圾回收消耗时间
GCT:垃圾回收消耗总时间

五、jmap

用于输出java程序中内存对象的情况,包括有哪些对象,对象的数量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
jmap -histo 18591
num #instances #bytes class name
----------------------------------------------
1: 631652 64523944 [C
2: 179202 57308168 [B
3: 32920 23425720 [I
4: 587502 14100048 java.lang.String
5: 346589 11090848 java.util.ArrayList$Itr
6: 135337 5917832 [Ljava.lang.Object;
7: 168929 5405728 java.util.HashMap$Node
8: 81666 4573296 java.util.concurrent.ConcurrentHashMap$ValueIterator
9: 76926 4307856 java.util.concurrent.ConcurrentHashMap$KeyIterator
10: 107003 4280120 java.util.HashMap$EntryIterator
11: 70716 3394368 java.util.HashMap
12: 140482 3371568 java.util.ArrayList
13: 55494 3107664 java.util.LinkedHashMap
14: 34441 3030808 java.lang.reflect.Method
15: 26545 2785344 [Ljava.util.HashMap$Node;
16: 77308 2473856 java.util.LinkedHashMap$LinkedEntryIterator
17: 66838 2138816 java.util.concurrent.ConcurrentHashMap$Node
18: 68194 1636656 org.apache.kafka.common.internals.PartitionStates$PartitionState
19: 40476 1619040 java.util.HashMap$KeyIterator
20: 39732 1589280 java.util.LinkedHashMap$Entry
21: 13979 1557928 java.lang.Class
22: 13926 1225488 org.apache.naming.resources.FileDirContext$FileResourceAttributes
23: 29725 951200 java.util.LinkedList
24: 14451 924864 java.net.URL
25: 26984 863488 java.io.File
......
......
Total 3984505 254742192

上述命令打印出进程ID为18591的内存情况。但我们常用的方式是将指定进程的内存heap输出到外部文件,再由专门的heap分析工具进行分析,例如mat(Memory Analysis Tool),所以我们常用的命令是:

jmap -dump:live,format=b,file=heap.hprof 18591

六、jstack

导出线程栈

1
jstack 18591 > jstack.out

运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
2018-12-04 16:48:47
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.60-b23 mixed mode):

"Attach Listener" #59821 daemon prio=9 os_prio=0 tid=0x00007f3118047800 nid=0x68ad waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE

"pool-3-thread-3" #25984 prio=5 os_prio=0 tid=0x00007f30c4125800 nid=0x64ee waiting on condition [0x00007f30a2eae000]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x00000000c2b1cd90> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

"KPOLLER-CC-topic" #77 daemon prio=5 os_prio=0 tid=0x00007f30e1839000 nid=0x48f5 runnable [0x00007f30b7efd000]
java.lang.Thread.State: RUNNABLE
at sun.nio.ch.EPollArrayWrapper.epollWait(Native Method)
at sun.nio.ch.EPollArrayWrapper.poll(EPollArrayWrapper.java:269)
at sun.nio.ch.EPollSelectorImpl.doSelect(EPollSelectorImpl.java:79)
at sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86)
- locked <0x00000000c2ddb3b0> (a sun.nio.ch.Util$2)
- locked <0x00000000c2ddb3a0> (a java.util.Collections$UnmodifiableSet)
- locked <0x00000000c2ddb0d0> (a sun.nio.ch.EPollSelectorImpl)
at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97)
at org.apache.kafka.common.network.Selector.select(Selector.java:684)
at org.apache.kafka.common.network.Selector.poll(Selector.java:408)
at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:460)
at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:261)
at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:233)
at org.apache.kafka.clients.consumer.KafkaConsumer.pollOnce(KafkaConsumer.java:1171)
at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1115)
"main" #1 prio=5 os_prio=0 tid=0x00007f315000c000 nid=0x48a0 runnable [0x00007f3157be7000]
java.lang.Thread.State: RUNNABLE
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:409)
at java.net.ServerSocket.implAccept(ServerSocket.java:545)
at java.net.ServerSocket.accept(ServerSocket.java:513)
at org.apache.catalina.core.StandardServer.await(StandardServer.java:470)
at org.apache.catalina.startup.Catalina.await(Catalina.java:781)
at org.apache.catalina.startup.Catalina.start(Catalina.java:727)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:294)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:428)

"VM Thread" os_prio=0 tid=0x00007f3150079800 nid=0x48a5 runnable

"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00007f3150021000 nid=0x48a1 runnable

"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00007f3150023000 nid=0x48a2 runnable

"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00007f3150024800 nid=0x48a3 runnable

"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00007f3150026800 nid=0x48a4 runnable

"VM Periodic Task Thread" os_prio=0 tid=0x00007f31500d7800 nid=0x48af waiting on condition

JNI global references: 11741

七、printf将线程tid转换为16进制

1
2
[admin@10-57-19-253 ~]$ printf '%x\n' 18677
48f5

八、vmstat

查看系统CPU/内存、swap、io等情况 ; vmstat interval count:每隔1秒输出一个结果,共5次

1
2
3
4
5
6
7
8
[admin@10-57-19-253 ~]$ vmstat 1 5
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
1 0 0 5941272 2068 1009732 0 0 0 0 0 0 0 0 100 0 0
0 0 0 5941272 2068 1009732 0 0 0 12 392 394 0 0 100 0 0
0 0 0 5941272 2068 1009732 0 0 0 54 410 440 0 0 100 0 0
0 0 0 5941272 2068 1009732 0 0 0 0 363 381 0 0 100 0 0
0 0 0 5941272 2068 1009732 0 0 0 0 358 384 0 0 100 0 0

解析:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
进程
r: 运行队列中进程数量,这个值也可以判断是否需要增加CPU。(长期大于1)
b: 等待IO的进程数量。

内存
swpd: 使用虚拟内存大小,如果swpd的值不为0,但是SI,SO的值长期为0,这种情况不会影响系统性能。
free: 空闲物理内存大小。
buff: 用作缓冲的内存大小。
cache: 用作缓存的内存大小,如果cache的值大的时候,说明cache处的文件数多,如果频繁访问到的文件都能被cache处,那么磁盘的读IO bi会非常小。

Swap
si:每秒从交换区写到内存的大小,由磁盘调入内存。
so:每秒写入交换区的内存大小,由内存调入磁盘。

CPU
us:用户进程执行时间百分比(user time) us的值比较高时,说明用户进程消耗的CPU时间多,但是如果长期超50%的使用,那么我们就该考虑优化程序算法或者进行加速。
sy:内核系统进程执行时间百分比(system time) sy的值高时,说明系统内核消耗的CPU资源多,这并不是良性表现,我们应该检查原因。
wa:IO等待时间百分比 wa的值高时,说明IO等待比较严重,这可能由于磁盘大量作随机访问造成,也有可能磁盘出现瓶颈(块操作)。
id: 空闲时间百分比

九、应用

查看哪个线程占用内存最高问题

1
2
3
4
5
1) `top` 查看内存和CPU使用最高的进程PID
2)`jstack PID > jstack.out` 导出线程栈
3) `top -Hp PID` 查看该进程内各线程使用内存和CPU情况,和进程tid
4)`printf '%x\n' tid`将进程`tid`转换为16进制
5)根据4步骤输出结果去2步骤输出结果`jstack.out`里面检索

十、参考地址

https://www.cnblogs.com/leefreeman/p/7464179.html

https://www.cnblogs.com/xqzt/p/5448983.html

https://github.com/oldratlee/useful-scripts

]]>
<h4 id="一、uptime"><a href="#一、uptime" class="headerlink" title="一、uptime"></a>一、uptime</h4><p>查看系统负载</p> <figure class="highlight plain"><ta
Java JWT 生成token https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/11/29/Java-JWT-生成token/ 2018-11-29T09:34:18.000Z 2018-11-29T09:35:10.525Z Java JWT 生成token

JSON Web Token for Java and Android

Maven依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.5</version>
<scope>runtime</scope>
</dependency>

JWT参数说明

1
2
3
4
5
6
7
iss: jwt签发者
sub: jwt所面向的用户
aud: 接收jwt的一方
exp: jwt的过期时间,这个过期时间必须要大于签发时间
nbf: 定义在什么时间之前,该jwt都是不可用的.
iat: jwt的签发时间
jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击。

JWT 简单代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package jwt;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.UUID;

/**
* <p>JWT 生成token</p>
*
* @author: zhengyong Date: 2018/11/29 Time: 下午4:48
*/
public class JwtTest {

/**
* 利用JWT生成token
*
* @return token
*/
public static String generateToken(Key key) {
/**
// 以下算法过程是注释伪代码步骤
String header = "{\"alg\":\"HS256\"}";
String body = "{\"sub\":\"Joe\"}";
String encodedHeader = base64URLEncode( header.getBytes("UTF-8"));
String encodedClaims = base64URLEncode( claims.getBytes("UTF-8") );
String concatenated = encodedHeader + "." + encodedClaims;
Key key = getMySecretKey();
byte[] signature = hmacSha256( concatenated, key );
String jws = concatenated + '.' + base64URLEncode( signature );
**/
// We need a signing key, so we'll create one just for this example. Usually
// the key would be read from your application configuration instead.
String jws = Jwts.builder()
.setIssuer("me")
.setSubject("Bob")
.setAudience("you")
// .setExpiration(expiration) //a java.util.Date
// .setNotBefore(notBefore) //a java.util.Date
.setIssuedAt(new Date()) // for example, now
.setId(UUID.randomUUID().toString()).signWith(key).compact(); //just an example id
return jws;
}

/**
* 验证token
*/
public static Jws validateToken(String jwsToken, Key key) {
try {

Jws<Claims> claimsJws = Jwts.parser().setSigningKey(key).parseClaimsJws(jwsToken);
//OK, we can trust this JWT
return claimsJws;
} catch (JwtException e) {
//don't trust the JWT!
e.printStackTrace();
}
System.out.println("error");
return null;
}

public static void main(String[] args) {
Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
// 生成token
String token = generateToken(key);
System.out.println("token:" + token);

// 解析验证token
Jws jws = validateToken(token, key);
System.out.println(JSON.toJSONString(jws));
}
}

参考地址

https://github.com/jwtk/jjwt

]]>
<h3 id="Java-JWT-生成token"><a href="#Java-JWT-生成token" class="headerlink" title="Java JWT 生成token"></a>Java JWT 生成token</h3><blockquote> <p>J
spring cache基于redis实现 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/11/26/spring-cache基于redis实现/ 2018-11-26T07:40:37.000Z 2018-11-26T08:26:27.781Z 一、概述
1
2
3
4
5
6
7
8
9
10
11
12
Spring 3.1 引入了激动人心的基于凝视(annotation)的缓存(cache)技术,它本质上不是一个具体的缓存实现方案(比如EHCache 或者 OSCache),而是一个对缓存使用的抽象,通过在既有代码中加入少量它定义的各种 annotation,即能够达到缓存方法的返回对象的效果。

Spring 的缓存技术还具备相当的灵活性。不仅能够使用 SpEL(Spring Expression Language)来定义缓存的 key 和各种 condition,还提供开箱即用的缓存暂时存储方案,也支持和主流的专业缓存比如 EHCache 集成。

其特点总结例如以下:

通过少量的配置 annotation 凝视就可以使得既有代码支持缓存
支持开箱即用 Out-Of-The-Box,即不用安装和部署额外第三方组件就可以使用缓存
支持 Spring Express Language,能使用对象的不论什么属性或者方法来定义缓存的 key 和 condition
支持 AspectJ,并通过事实上现不论什么方法的缓存支持
支持自己定义 key 和自己定义缓存管理者,具有相当的灵活性和扩展性
本文将针对上述特点对 Spring cache 进行具体的介绍,主要通过一个简单的样例和原理介绍展开,然后我们将一起看一个比較实际的缓存样例。最后会介绍 spring cache 的使用限制和注意事项。

二、曾经我们如何实现缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {
// 1. 先查询缓存数据
String cacheData = redisClient.get("key");
// 2. 缓存数据不存在,查询数据库,查询到数据再放入缓存
if(cacheData == null) {
cacheData = loadFromDB("key");
redisClient.put("key", cacheData);
}
}

public static String loadFromDB(String key) {
System.out.println("query data from db, key=" + key);
}

三、利用spring Cache如何实现缓存

1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
// 1. 一句话实现自动保存缓存
String cacheData = cacheData = loadFromDB("key");
}

@Cacheable(value = "myCache", key = "#p0")
public static String loadFromDB(String key) {
System.out.println("query data from db, key=" + key);
}

四、spring Cache实现简单示列(ConcurrentMap)

1
2
3
4
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
1)XML定义
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

<!-- spring cache config-->
<cache:annotation-driven/>
<bean id="userService" class="springcache.UserService"/>
<bean id="redisCustomCache" class="springcache.RedisCustomCache"/>
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default"></bean>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="userCache"></bean>
</set>
</property>
</bean>

</beans>
2)缓存方法实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package springcache;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

/**
* @author: zhengyong Date: 2018/11/23 Time: 上午10:51
*/
public class UserService {

// key="#p0" (https://stackoverflow.com/questions/29862053/spring-cache-null-key-returned-for-cache-operation)
@Cacheable(value = "userCache", key = "#p0")
public String getUserName(String id) {
return getFromDB(id);
}

@CachePut(value = "userCache", key = "#p0")
public String updateUser(String id, String name) {
return getFromDB(id);
}

@CacheEvict(value = "userCache", key = "#p0")
public void deleteUser(String id) {
System.out.println("delete username from db, id=" + id);
}

private String getFromDB(String id) {
System.out.println("query username from db, id=" + id);
return String.format("username-%s", id);
}
}
3)测试类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package springcache;

import org.apache.log4j.xml.DOMConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* <p>https://www.ibm.com/developerworks/cn/opensource/os-cn-spring-cache/index.html</p>
* <p>
* Created by zhengyong on 17/3/3.
*/
public class SpringCacheTest {

public static void main(String[] args) {

UserService userService = (UserService) ctx.getBean("userService");

System.out.println(" ---- @Cacheable test ----");
userService.getUserName("st1");
userService.getUserName("st1");
userService.getUserName("st1");
userService.getUserName("st2");
userService.getUserName("st3");
userService.getUserName("st4");
userService.getUserName("st4");

System.out.println(" \n \n");

System.out.println(" ---- @CachePut test ----");
userService.updateUser("st1", null);
userService.updateUser("st1", null);
userService.updateUser("st1", null);
userService.updateUser("st2", null);
userService.updateUser("st3", null);
userService.updateUser("st4", null);
userService.updateUser("st4", null);

System.out.println(" \n \n");

System.out.println(" ---- @CacheEvict test ----");
userService.getUserName("st1");
userService.deleteUser("st1");
userService.getUserName("st1");

}
}
4)运行结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 ----  @Cacheable test ----
query username from db, id=st1
query username from db, id=st2
query username from db, id=st3
query username from db, id=st4

---- @CachePut test ----
query username from db, id=st1
query username from db, id=st1
query username from db, id=st1
query username from db, id=st2
query username from db, id=st3
query username from db, id=st4
query username from db, id=st4

---- @CacheEvict test ----
delete username from db, id=st1
query username from db, id=st1

五、spring Cache高级扩展(Redis)

1) 自定义cache实现,实现接口org.springframework.cache.Cache

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package springcache;

import com.alibaba.fastjson.JSON;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import redis.clients.jedis.Jedis;
import serialization.hessian.HessianUtil;

import java.util.Set;

/**
* <p>spring cache redis实现</p>
*
* @author: zhengyong Date: 2018/11/23 Time: 上午11:46
*/
public class RedisCustomCache implements Cache {

private Jedis jedis;

private String name;

@Override
public String getName() {
return this.name;
}

@Override
public Object getNativeCache() {
return this.jedis;
}

@Override
public ValueWrapper get(Object key) {
byte[] keyByte = getKeyByte(key);
byte[] value = jedis.get(keyByte);
if (value == null) {
return null;
}
Object object = null;
try {
object = HessianUtil.decoder(value);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("get data from redis, key=" + key + "; value=" + JSON.toJSONString(object));
ValueWrapper obj = (object != null ? new SimpleValueWrapper(object) : null);
return obj;
}

@Override
public void put(Object key, Object value) {
if (value == null) {
return;
}
byte[] keyByte = getKeyByte(key);
byte[] encoderValue = new byte[0];
System.out.println("put data into redis, key=" + key + "; value=" + JSON.toJSONString(value));
try {
encoderValue = HessianUtil.encoder(value);
} catch (Exception e) {
e.printStackTrace();
}
jedis.set(keyByte, encoderValue);
}

@Override
public void evict(Object key) {
byte[] keyByte = getKeyByte(key);
jedis.del(keyByte);
}

@Override
public void clear() {
// TODO
}

private byte[] getKeyByte(Object key) {
return key.toString().getBytes();
}

public void setName(String name) {
this.name = name;
}

public void setJedis(Jedis jedis) {
this.jedis = jedis;
}
}

1.1)HessianUtil 序列化工具类实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package serialization.hessian;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.SerializerFactory;

/**
* <p>
* hessian2 序列化和反序列化
* </p>
* Created by zhengyong on 17/5/27.
*/
public class HessianUtil {

/**
* 序列化数据
*
* @param message
* @throws Exception
*/
public static byte[] encoder(Object message) throws Exception {

ByteArrayOutputStream byteOutputStream = null;
// hessian解析二进制
Hessian2Output hessian2Output = null;
try {
byteOutputStream = new ByteArrayOutputStream();
hessian2Output = new Hessian2Output(byteOutputStream);
/**
* 设置serializerFactory能将hessian序列化的效率提高几倍,如果不设置会导致最初的几次序列化效率低,出现阻塞的情况。
* 主要原因是如果hessian2Output中的serializerFactory为空的话,writeObject的时候创建这个对象的时候会出现阻塞,导致最初几次调用耗时过长
*/
SerializerFactory factory = new SerializerFactory();
hessian2Output.setSerializerFactory(factory);
// 写入序列化信息
// hessian2Output.startMessage();
hessian2Output.writeObject(message);
// hessian2Output.completeMessage();

hessian2Output.flush(); // 将序列化信息发送出去

byte[] data = byteOutputStream.toByteArray();

return data;
} finally {
if (byteOutputStream != null) {
byteOutputStream.close();
}
if (hessian2Output != null) {
hessian2Output.close();
}
}
}

/**
* 反序列化二进制数据
*
* @param data
* @return Object
* @throws Exception
*/
public static Object decoder(byte[] data) throws Exception {

ByteArrayInputStream is = null;
// hessian解析二进制
Hessian2Input hessian2Input = null;
try {
is = new ByteArrayInputStream(data);
hessian2Input = new Hessian2Input(is);
/**
* 设置serializerFactory能将hessian序列化的效率提高几倍,如果不设置会导致最初的几次序列化效率低,出现阻塞的情况
*/
SerializerFactory factory = new SerializerFactory();
hessian2Input.setSerializerFactory(factory);
// hessian反序列化对象
//hessian2Input.startMessage();
Object ret = hessian2Input.readObject();
//hessian2Input.completeMessage();
return ret;
} finally {
if (is != null) {
is.close();
}
if (hessian2Input != null) {
hessian2Input.close();
}
}
}

}

2) XML修改为如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

<!-- spring cache config-->
<cache:annotation-driven/>
<bean id="userService" class="springcache.UserService"/>
<bean id="redisCustomCache" class="springcache.RedisCustomCache"/>
<!-- redis地址配置 -->
<bean id="jedisBean" class="redis.clients.jedis.Jedis" >
<constructor-arg name="host" value="127.0.0.1" />
<constructor-arg name="port" value="6379" />
<constructor-arg name="timeout" value="100000" />
</bean>
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default"></bean>
<!-- 自定义redis cache实现 -->
<bean class="springcache.RedisCustomCache">
<property name="jedis" ref="jedisBean"></property>
<property name="name" value="userCache"></property>
</bean>
</set>
</property>
</bean>

</beans>
3)运行结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 ----  @Cacheable test ----
query username from db, id=st1
put data into redis, key=st1; value="username-st1"
get data from redis, key=st1; value="username-st1"
get data from redis, key=st1; value="username-st1"
query username from db, id=st2
put data into redis, key=st2; value="username-st2"
put data into redis, key=st3; value="username-st3"
query username from db, id=st4
put data into redis, key=st4; value="username-st4"
query username from db, id=st4
get data from redis, key=st4; value="username-st4"

---- @CachePut test ----
query username from db, id=st1
put data into redis, key=st1; value="username-st1"
query username from db, id=st1
put data into redis, key=st1; value="username-st1"
query username from db, id=st1
put data into redis, key=st1; value="username-st1"
query username from db, id=st2
put data into redis, key=st2; value="username-st2"
query username from db, id=st3
put data into redis, key=st3; value="username-st3"
query username from db, id=st4
put data into redis, key=st4; value="username-st4"
query username from db, id=st4
put data into redis, key=st4; value="username-st4"

---- @CacheEvict test ----
get data from redis, key=st1; value="username-st1"
delete username from db, id=st1
query username from db, id=st1
put data into redis, key=st1; value="username-st1"

六、参考地址

1)https://www.ibm.com/developerworks/cn/opensource/os-cn-spring-cache/index.html

七、项目源码

https://github.com/zyongjava/pomelo/blob/master/src/main/java/springcache/SpringCacheTest.java

]]>
<h3 id="一、概述"><a href="#一、概述" class="headerlink" title="一、概述"></a>一、概述</h3><figure class="highlight plain"><table><tr><td class="gutter"><pr
spring boot 全局Controller错误处理器 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/11/14/spring-boot-全局Controller错误处理器/ 2018-11-14T08:57:35.000Z 2018-11-14T09:27:05.135Z 背景

SpringBoot默认有自定义异常处理的体系,在做SpringBoot项目的时候,如果是抛出了运行时异常,springBoot并会对异常进行处理;

1
2
3
4
5
6
7
8
1. json接口返回如下异常信息:
{
"timestamp": 1478571808052,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/json/rpc"
}
1
2
3
4
5
6
7
8
9
2. html接口返回如下信息:

Whitelabel Error Page

This application has no explicit mapping for /html/rpc, so you are seeing this as a fallback.

Thu Sep 07 16:27:43 CST 2018
There was an unexpected error (type=Not Found, status=404).
No message available

追究其原因,发现SpirngBoot出现异常信息时候,会默认访问/error,springBoot种有BasicErrorController这个类来处理异常信息.

改造

我们通过继承ErrorController,实现自己的处理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package cn.pomelo.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

/**
* 统一错误处理。<br/>
*
* @see {http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-customize-the-whitelabel-error-page}
* @see {http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling} <br/>
*/
@Controller
public class CommonErrorController implements ErrorController {

private static final Logger logger = LoggerFactory.getLogger(CommonErrorController.class);

public final static String ERROR_PATH = "/error";

@Autowired
private ErrorAttributes errorAttributes;

/**
* Supports other formats JSON
*
* @param request HttpServletRequest
* @return ResponseEntity
*/
@RequestMapping(value = ERROR_PATH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request);
HttpStatus status = getStatus(request);
return JSON.toJSONString(new ResponseEntity<>(body, status).getBody());
}

/**
* Supports the HTML Error View
*
* @param request HttpServletRequest
* @return ModelAndView
*/
@RequestMapping(value = ERROR_PATH, produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request) {
return new ModelAndView("globalError", getErrorAttributes(request));
}

/**
* 错误信息详情map
*
* @param request
* @return ErrorAttributes
*/
private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
Map<String, Object> map = errorAttributes.getErrorAttributes(requestAttributes, isTrace(request));
if (request.getAttribute("status") instanceof Integer) {
map.put("status", request.getAttribute("status"));
}
map.put("url", request.getRequestURL().toString());
map.putIfAbsent("path", request.getAttribute("raw_url"));
if (logger.isInfoEnabled()) {
logger.info("error occurred, status={}, path={}, msg={}, error={}, exception={}", map.get("status"),
map.get("path"), map.get("message"), map.get("error"), map.get("exception"));
}
return map;
}

/**
* 获取状态码
*
* @param request HttpServletRequest
* @return HttpStatus
*/
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}

/**
* 是否打印错误信息
*
* @param request HttpServletRequest
* @return if trace error
*/
private boolean isTrace(HttpServletRequest request) {
String parameter = request.getParameter("trace");
if (parameter == null) {
return false;
}
return !"false".equals(parameter.toLowerCase());
}

@Override
public String getErrorPath() {
return ERROR_PATH;
}
}
修改后结果:
1
2
3
4
5
6
1. json返回:
{
"status": 404
"url": "/json/rpc",
"path": "/json/rpc?p=1"
}
1
2
2. html页面返回:
渲染视图:globalError.html
]]>
<h4 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h4><p>SpringBoot默认有自定义异常处理的体系,在做SpringBoot项目的时候,如果是抛出了运行时异常,springBoot并会对异常进
redis分布式锁 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/11/12/redis分布式锁/ 2018-11-12T09:00:17.000Z 2018-11-12T09:02:01.111Z 工具类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package redis;

import org.apache.commons.lang3.math.NumberUtils;
import redis.clients.jedis.Jedis;

import java.util.Objects;

/**
* <pre>https://blog.csdn.net/rich_family/article/details/79034808</pre>
*
* @author: zhengyong Date: 2018/7/6 Time: 下午5:32
*/
public class RedisDistributedLock {


/**
* 获取锁直到成功
*
* @param jedis redis客户端
* @param key 锁key
* @param timeout 锁超时时间
*/
public void tryLockSuccess(Jedis jedis, String key, long timeout) {
// 一直循环直到获取到锁
while (!this.tryLock(jedis, key, timeout)) {
}
}

/**
* 获取锁
*
* @param jedis redis客户端
* @param key 锁key
* @param timeout 锁超时时间
* @return true / false
*/
public boolean tryLock(Jedis jedis, String key, long timeout) {
long currentTime = System.currentTimeMillis();
String expires = String.valueOf(timeout + currentTime);
//设置互斥量
if (jedis.setnx(key, expires) > 0) {
return true;
} else {
// 未获取到锁,判断锁是否超时
String currentLockTime = jedis.get(key);
//检查锁是否超时, 如果超时,尝试获取锁
if (currentLockTime != null && Long.parseLong(currentLockTime) < currentTime) {
//获取旧的锁时间并设置互斥量
String oldLockTime = jedis.getSet(key, expires);
//旧值与当前时间比较
if (oldLockTime != null && Objects.equals(oldLockTime, currentLockTime)) {
return true;
}
}
return false;
}
}

/**
* 释放锁(如果锁已超时,那么锁可能已由其他线程获得,这时直接执行 DEL lock.id 操作会导致把其他线程已获得的锁释放掉。所以这里只删除未超时的lock.id)
*
* @param jedis redis客户端
* @param key 锁key
* @return true / false
*/
public boolean unlock(Jedis jedis, String key) {
//判断锁是否超时,没有超时才将互斥量删除
String expire = jedis.get(key);
long lockExpiresTime = NumberUtils.toLong(expire);
if (lockExpiresTime > System.currentTimeMillis()) {
jedis.del(key);
}
return true;
}

}
测试类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package redis;

import redis.clients.jedis.Jedis;

/**
* @author: zhengyong Date: 2018/7/6 Time: 下午5:56
*/
public class RedisTest {
/**
* redis ip
*/
private static final String redisHost = "127.0.0.1";
/**
* redis 端口
*/
private static final int redisPort = 6379;
/**
* redis读取超时时间
*/
private static final int redisTimeout = 1000000;
/**
* 锁超时2秒
*/
private static final long lockTimeout = 2000;

private static RedisDistributedLock lock = new RedisDistributedLock();

private static int count = 0;

public static void main(String[] args) throws InterruptedException {
// 多线程测试分布式锁
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
Jedis jedis = new Jedis(redisHost, redisPort, redisTimeout);
execute(jedis);
}
}).start();
}
Thread.sleep(3000);
System.out.println(count);
}

private static void execute(Jedis jedis) {
String key = "execute";
// 获取分布式锁
lock.tryLockSuccess(jedis, key, lockTimeout);
try {
count++;
} finally {
lock.unlock(jedis, key);
}
}
}
]]>
<h5 id="工具类:"><a href="#工具类:" class="headerlink" title="工具类:"></a>工具类:</h5><figure class="highlight plain"><table><tr><td class="gutter"><pr
java8-lambda表达式之stream https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/11/12/java8-lambda表达式之stream/ 2018-11-12T07:52:47.000Z 2018-11-12T07:54:48.775Z Stream API

新添加的Stream API(java.util.stream) 把真正的函数式编程风格引入到Java中。

示列代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package java8.lambda;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

/**
* java 8 lambada 基础操作(http://www.runoob.com/java/java8-streams.html)
*
* @author: zhengyong Date: 2018/11/1 Time: 上午10:49
*/
public class Test {

public static void main(String[] args) {

//Runnable是一个函数接口,只包含了有个无参数的,返回void的run方法;
//所以lambda表达式左边没有参数,右边也没有return,只是单纯的打印一句话
new Thread(() -> System.out.println("Test Java8 lambda!")).start();

//In Java 8:
List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");

// 1. forEach: 迭代流中的每个数据
System.out.println("\n... 1. start forEach");
features.forEach(n -> System.out.println(n));

System.out.println("\n... 2. start stream ");
System.out.println("... 3. start map");
// 2. stream: 为集合创建串行流
// 3. map: 映射每个元素到对应的结果
features.stream().map((s) -> s + "***").forEach(System.out::println);

// 4. filter: 用于通过设置的条件过滤出元素
System.out.println("\n... 4. start filter");
features.stream().filter(f -> f.startsWith("L")).forEach(System.out::println);

// 5. limit: 用于获取指定数量的流
System.out.println("\n... 5. start limit");
features.stream().limit(2).forEach(System.out::println);

// 6. sorted: 用于对流进行排序
System.out.println("\n... 6. start sorted");
features.stream().sorted().forEach(System.out::println);

// 7. parallel: 为集合创建并行流
System.out.println("\n... 7. start parallel stream");
features.parallelStream().filter(f -> f.startsWith("L")).forEach(System.out::println);

// 8.Collectors :实现了很多归约操作
System.out.println("\n... 8. start Collectors");
List<String> list = features.stream().filter(f -> f.startsWith("L")).collect(Collectors.toList());
String str = features.stream().filter(f -> !f.isEmpty()).collect(Collectors.joining(","));
System.out.println("Collectors list=" + list);
System.out.println("Collectors str=" + str);

// 9. summaryStatistics: 统计结果的收集器也非常有用。它们主要用于int、double、long等基本类型上
System.out.println("\n... 8. start summaryStatistics");
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = numbers.stream().mapToInt(x -> x).summaryStatistics();
System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());
}
}
运行结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Test Java8 lambda!

... 1. start forEach
Lambdas
Default Method
Stream API
Date and Time API

... 2. start stream
... 3. start map
Lambdas***
Default Method***
Stream API***
Date and Time API***

... 4. start filter
Lambdas

... 5. start limit
Lambdas
Default Method

... 6. start sorted
Date and Time API
Default Method
Lambdas
Stream API

... 7. start parallel stream
Lambdas

... 8. start Collectors
Collectors list=[Lambdas]
Collectors str=Lambdas,Default Method,Stream API,Date and Time API

... 8. start summaryStatistics
列表中最大的数 : 7
列表中最小的数 : 2
所有数之和 : 25
平均数 : 3.5714285714285716
]]>
<h4 id="Stream-API"><a href="#Stream-API" class="headerlink" title="Stream API"></a>Stream API</h4><p>新添加的Stream API(java.util.stream) 把真正的函
awk使用 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/09/05/awk使用/ 2018-09-05T07:49:34.000Z 2018-09-05T08:52:24.562Z 首先建立文本log.txt:

1
2
3
4
2 this is a test
3 Are you like awk
This's a test
10 There are orange,apple,mongo

A. 每行按空格或TAB分割,输出文本中的1、4项, 例如:awk '{print $1,$4}' log.txt

1
2
3
4
5
6
$ awk '{print $1,$4}' log.txt

2 a
3 like
This's
10 orange,apple,mongo

B. 使用”,”分割,例如:awk -F, '{print $1,$2}' log.txt

1
2
3
4
5
6
$ awk -F, '{print $1,$2}' log.txt

2 this is a test
3 Are you like awk
This's a test
10 There are orange apple

C. 使用多个分隔符.先使用空格分割,然后对分割结果再使用”,”分割. 例如:awk -F '[ ,]' '{print $1,$2,$5}' log.txt

1
2
3
4
5
6
$ awk -F '[ ,]'  '{print $1,$2,$5}' log.txt

2 this test
3 Are awk
This's a
10 There apple

D. 使用awk -v设置变量a=1, 例如:awk -v a=1 '{print $1,$1+a}' log.txt

1
2
3
4
5
6
$ awk -v a=1 '{print $1,$1+a}' log.txt

2 3
3 4
This's 1
10 11

E. 使用脚本,例如:awk -f cal.awk log.txt

F. awk使用运算符

1) 过滤第一例大于2的行. 例如:awk '$1>2' log.txt

2) 过滤第一列大于2并且第二列等于’Are’的行. 例如:awk '$1>2 && $2=="Are" {print $1,$2,$3}' log.txt

G. awk正使用则表达式

注意:~ 表示模式开始。// 中是模式。

例子:

1
2
3
4
# 输出第二列包含 "th",并打印第二列与第四列
$ awk '$2 ~ /th/ {print $2,$4}' log.txt
---------------------------------------------
this a
1
2
3
4
5
# 输出包含"re" 的行
$ awk '/re/ ' log.txt
---------------------------------------------
3 Are you like awk
10 There are orange,apple,mongo
1
2
3
4
5
# 忽略大小写
$ awk 'BEGIN{IGNORECASE=1} /this/' log.txt
---------------------------------------------
2 this is a test
This's a test

H. awk脚本

BEGIN{ 这里面放的是执行前的语句 }

END {这里面放的是处理完所有的行后要执行的语句 }

{这里面放的是处理每一行时要执行的语句}

例如cal.awk内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/bin/awk -f
#运行前
BEGIN {
math = 0
english = 0
computer = 0

printf "NAME NO. MATH ENGLISH COMPUTER TOTAL\n"
printf "---------------------------------------------\n"
}
#运行中
{
math+=$3
english+=$4
computer+=$5
printf "%-6s %-6s %4d %8d %8d %8d\n", $1, $2, $3,$4,$5, $3+$4+$5
}
#运行后
END {
printf "---------------------------------------------\n"
printf " TOTAL:%10d %8d %8d \n", math, english, computer
printf "AVERAGE:%10.2f %8.2f %8.2f\n", math/NR, english/NR, computer/NR
}

G. 统计行数

1
awk '/error/' app.log | awk 'END {print NR}'

或者:

1
grep -c 'error' app.log

参考:http://www.runoob.com/linux/linux-comm-awk.html

]]>
<p>首先建立文本<code>log.txt</code>:</p> <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span c
docker使用 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/09/05/docker使用/ 2018-09-05T07:46:20.000Z 2018-09-05T07:53:05.050Z 一、简介

Docker 和传统虚拟化方式的不同之处。传统虚拟机技术是虚拟出一套硬件后,在其上运行一个完整操作系统,在该系统上再运行所需应用进程;而容器内的应用进程直接运行于宿主的内核,容器内没有自己的内核,而且也没有进行硬件虚拟。因此容器要比传统虚拟机更为轻便

镜像(Image)和容器(Container)的关系,就像是面向对象程序设计中的类和实例一样,镜像是静态的定义,容器是镜像运行时的实体。容器可以被创建、启动、停止、删除、暂停等

二、安装须知

操作系统: Mac OS Yosemite 10.10.5

Mac地址:https://download.docker.com/mac/stable/Docker.dmg

Docker.dmg:安装提供Docker Engine,Docker CLI客户端,Docker Compose和Docker Machine

三、安装

1)运行Docker.dmg安装

2)配置个人加速镜像(我使用阿里云https://cr.console.aliyun.com/#/accelerator)

3) 运行docker version和docker info检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
➜ docker version
Client:
Version: 17.03.0-ce
API version: 1.26
Go version: go1.7.5
Git commit: 60ccb22
Built: Thu Feb 23 10:40:59 2017
OS/Arch: darwin/amd64

Server:
Version: 17.03.0-ce
API version: 1.26 (minimum version 1.12)
Go version: go1.7.5
Git commit: 3a232c8
Built: Tue Feb 28 07:52:04 2017
OS/Arch: linux/amd64
Experimental: true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
➜ docker info
Containers: 1
Running: 1
Paused: 0
Stopped: 0
Images: 1
Server Version: 17.03.0-ce
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
Volume: local
Network: bridge host ipvlan macvlan null overlay
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 977c511eda0925a723debdc94d09459af49d082a
runc version: a01dafd48bc1c7cc12bdb01206f9fea7dd6feb70
init version: 949e6fa
Security Options:
seccomp
Profile: default
Kernel Version: 4.9.12-moby
Operating System: Alpine Linux v3.5
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 1.952 GiB
Name: moby
ID: V5PN:CAOJ:YYKT:B7IK:PTP3:OQKS:Q26Q:UJYZ:OG2K:HSPK:WRME:KJP5
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
File Descriptors: 23
Goroutines: 32
System Time: 2017-03-27T03:33:06.945792584Z
EventsListeners: 1
No Proxy: 127.0.0.1
Registry: https://index.docker.io/v1/
Experimental: true
Insecure Registries:
127.0.0.0/8
Registry Mirrors:
https://xxxxx.mirror.aliyuncs.com
Live Restore Enabled: false

四、运行nginx

启动运行nginx, 执行docker run -d -p 80:80 --name webserver nginx

1
2
3
4
5
6
7
8
9
➜ docker run -d -p 80:80 --name webserver nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
693502eb7dfb: Pull complete
6decb850d2bc: Pull complete
c3e19f087ed6: Pull complete
Digest: sha256:52a189e49c0c797cfc5cbfe578c68c225d160fb13a42954144b29af3fe4fe335
Status: Downloaded newer image for nginx:latest
4b11e6ed897d6df195936f60916ffda704d55f75645270f338a10b68480112e7

启动bash命令交互操作客户端

1
2
➜ docker exec -it webserver bash
root@2964bd62006a:/#

停止niginx, 运行docker stop webserver

1
2
➜ docker stop webserver
webserver

删除nginx, 运行docker rm webserver

1
2
➜ docker rm webserver
webserver

五、运行ubuntu

镜像官方仓库:https://hub.docker.com/explore/

下载ubuntu

1
2
3
4
5
6
7
8
9
➜ docker pull ubuntu:14.04
14.04: Pulling from library/ubuntu
30d541b48fc0: Pull complete
8ecd7f80d390: Pull complete
46ec9927bb81: Pull complete
2e67a4d67b44: Pull complete
7d9dd9155488: Pull complete
Digest: sha256:62a5dce5ceccd7f1cb2672a571ebee52cad1f08eec9b57fe4965fb0968a9602e
Status: Downloaded newer image for ubuntu:14.04

启动运行ubuntu

-it:这是两个参数,一个是 -i:交互式操作,一个是 -t 终端。我们这里打算进入 bash 执行一些命令并查看返回结果,因此我们需要交互式终端。

–rm:这个参数是说容器退出后随之将其删除。默认情况下,为了排障需求,退出的容器并不会立即删除,除非手动 docker rm。我们这里只是随便执行个命令,看看结果,不需要排障和保留结果,因此使用 –rm 可以避免浪费空间。

ubuntu:14.04:这是指用 ubuntu:14.04 镜像为基础来启动容器。

–name myUbuntu:给容器取一个别名叫myUbuntu

1
2
➜ docker run -it --rm --name myUbuntu ubuntu:14.04
root@2ef73a93ef7b:/#

或者不指定ubuntu版本,直接启动时,直接下载最新版本ubuntu:latest

1
2
3
4
5
6
7
8
9
10
11
➜ docker run -it --name myUbuntu ubuntu:14.04
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
d54efb8db41d: Pull complete
f8b845f45a87: Pull complete
e8db7bf7c39f: Pull complete
9654c40e9079: Pull complete
6d9ef359eaaa: Pull complete
Digest: sha256:dd7808d8792c9841d0b460122f1acf0a2dd1f56404f8d1e56298048885e45535
Status: Downloaded newer image for ubuntu:latest
root@366ea11633cf:/#

停止ubuntu容器

1
2
➜ docker stop myUbuntu
myUbuntu

删除ubuntu容器

1
2
➜ docker rm myUbuntu
myUbuntu

查看历史镜像

1
2
3
4
➜ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 6b914bbcb89e 3 weeks ago 182 MB
ubuntu 14.04 7c09e61e9035 3 weeks ago 188 MB

删除ubuntu镜像

使用docker rmi <IMAGE ID>删除,但是必须先要docker rm myUbuntu才能删除镜像

1
2
3
4
5
6
7
8
9
➜ docker rmi 7c09e61e9035
Untagged: ubuntu:14.04
Untagged: ubuntu@sha256:62a5dce5ceccd7f1cb2672a571ebee52cad1f08eec9b57fe4965fb0968a9602e
Deleted: sha256:7c09e61e90350e8f5c0cba2979003bdfe32c2d027b68b4f0cf9063cdd7b4bafd
Deleted: sha256:304aecb5e13929f85d3ce2e9d83d0212866c8e55a460c94cf24bd75da1c7c153
Deleted: sha256:f302be18d46a45c0edbbd9b4bc02db764a4b0b8cd9bd0490f33dfaff039a3b62
Deleted: sha256:c523f3173f6028e5329fd401331c375f7b9b9e831d915fafaf358f55e36e3747
Deleted: sha256:94e631422130dc414878fd05efe3d59de44c9d8904696a7c299a83f378a92845
Deleted: sha256:c29b5eadf94a90a2abda13e765d4fad4825fd15621dea1d9a98b60b89b835c2a

查看docker进程

1
2
3
➜ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
366ea11633cf ubuntu "/bin/bash" About a minute ago Exited (0) 59 seconds ago myUbuntu

六、制作自定义nginx

1) 启动nginx

1
2
3
4
5
6
7
8
9
➜  docker run -d -p 80:80 --name webserver nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
693502eb7dfb: Pull complete
6decb850d2bc: Pull complete
c3e19f087ed6: Pull complete
Digest: sha256:52a189e49c0c797cfc5cbfe578c68c225d160fb13a42954144b29af3fe4fe335
Status: Downloaded newer image for nginx:latest
2964bd62006acd43611ea045e8152f651905e213c392e008a59eebe667080b3d

2) 启动bash控制台并修改index.html内容

1
2
3
4
5
6
➜  docker exec -it webserver bash
root@2964bd62006a:/# ls
bin boot devetc home liblib64 media mnt optproc root run sbin srv sys tmp usr var
root@2964bd62006a:/# echo '<h1>Hello, Docker!</h1>' > /usr/share/nginx/html/index.html
root@2964bd62006a:/# exit
exit

3)查看容器修改内容

1
2
3
4
5
6
7
8
9
10
11
12
➜  docker diff webserver
C /root
A /root/.bash_history
C /run
A /run/nginx.pid
C /usr/share/nginx/html/index.html
C /var/cache/nginx
A /var/cache/nginx/client_temp
A /var/cache/nginx/fastcgi_temp
A /var/cache/nginx/proxy_temp
A /var/cache/nginx/scgi_temp
A /var/cache/nginx/uwsgi_temp

4)制作v2版本tag的nginx

1
2
➜  docker commit --author "zhengyong" --message "update index.htm" webserver nigix:v2
sha256:b86a71250cf4e41a34af24b7e2924e3909ecdf74262195d6ac30fd57bbdbaf35

5) 启动v2版本nginx

1
2
➜  docker run -d -p 80:80 --name ng nigix:v2
72f15356de38c26456cdee8a68651a2de25e59d8f8e4ce31e82c434927ff4b4f

七、Dockerfile

1)创建工程目录和Dockerfile文件

1
2
3
➜ mkdir mynginx
➜ cd mynginx
➜ touch Dockerfile

2)Dockerfile文件内容

1
2
FROM nginx
RUN echo '<h1>Hello, Docker!</h1>' > /usr/share/nginx/html/index.html

3) 构建docker镜像

使用命令docker build -t nginx:v3 .构建:

1
2
3
4
5
6
7
8
9
➜ docker build -t nginx:v3 .
Sending build context to Docker daemon 2.048 kB
Step 1/2 : FROM nginx
---> 6b914bbcb89e
Step 2/2 : RUN echo '<h1>Hello, Docker!</h1>' > /usr/share/nginx/html/index.html
---> Running in a41235243cb9
---> 7a2e14fdfefb
Removing intermediate container a41235243cb9
Successfully built 7a2e14fdfefb

docker导致mac硬盘空间不足:

1
2
3
4
docker rm $(docker ps -a -q)
docker rmi $(docker images -q)
docker volume rm $(docker volume ls |awk '{print $2}')
rm -rf ~/Library/Containers/com.docker.docker/Data/*
]]>
<h4 id="一、简介"><a href="#一、简介" class="headerlink" title="一、简介"></a>一、简介</h4><blockquote> <p> Docker 和传统虚拟化方式的不同之处。传统虚拟机技术是虚拟出一套硬件后,在其上运行一个完整操
Drools使用 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/09/05/Drools使用/ 2018-09-05T07:44:42.000Z 2018-09-05T07:52:55.769Z Maven dependency
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-api</artifactId>
<version>6.5.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>6.5.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>6.5.0.Final</version>
</dependency>

Rule Syntax

1. Conditions in Rules

A rule can contain many conditions and patterns such as:

1
2
Account (balance == 200)
Customer (name == “Vivek”)

The above conditions check if the Account balance is 200 or the Customer name is “Vivek”.

2. Variables in Rules

A variable name in Drools starts with a Dollar($) symbol.

1
2
$account : Account( )
$account is the variable for Account() class

Drools can work with all the native Java types and even Enum.

3. Comments in Rules

The special characters, # or //, can be used to mark single-line comments.

For multi-line comments, use the following format:

1
2
3
4
5
/*
Another line
.........
.........
*/
4.Functions in Rules

Functions are a convenience feature. They can be used in conditions and consequences. Functions represent an alternative to the utility/helper classes. For example:

1
2
3
function double calculateSquare (double value) {
return value * value;
}
5. Salience (same as priority)

Salience is a very important feature of Rule Syntax. Salience is used by the conflict resolution strategy to decide which rule to fire first. By default, it is the main criterion.

We can use salience to define the order of firing rules. Salience has one attribute, which takes any expression that returns a number of type int (positive as well as negative numbers are valid). The higher the value, the more likely a rule will be picked up by the conflict resolution strategy to fire.

1
salience ($account.balance * 5)

The default salience value is 0. We should keep this in mind when assigning salience values to some rules only.

参考地址

https://www.tutorialspoint.com/drools/drools_rule_syntax.htm

]]>
<h3 id="Maven-dependency"><a href="#Maven-dependency" class="headerlink" title="Maven dependency"></a>Maven dependency</h3><figure class="hi
HashMap(JDK-1.8) https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/09/05/HashMap-JDK-1-8/ 2018-09-05T07:43:36.000Z 2018-09-05T07:52:47.298Z 一:resize扩容
  1. 当前table Node数组赋给临时变量,并记录老table的初始化容量和加载因子
  2. 如果老初始化容量大于0,新表初始化容量直接扩大为原来的2倍
  3. 循环老table,对新table赋值

1) 如果如果链表只有一个,则进行直接赋值newTab[e.hash & (newCap - 1)] = e

2)如果红黑二叉树:……

3)链表赋值,如果新表位置变化e.hash & oldCap) == 0, 则老表数据在新表位置为(老数组位置i+老数组容量oldCap)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
final Node<K, V>[] resize() {
Node<K, V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;// 数组长度
int oldThr = threshold;// 临界值
int newCap, newThr = 0;
if (oldCap > 0) {
// 扩容
if (oldCap >= MAXIMUM_CAPACITY) {
// 原数组长度大于最大容量(1073741824) 则将threshold设为Integer.MAX_VALUE=2147483647
// 接近MAXIMUM_CAPACITY的两倍
threshold = Integer.MAX_VALUE;
return oldTab;
} else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) {
// 新数组长度 是原来的2倍,
// 临界值也扩大为原来2倍
newThr = oldThr << 1;
}
} else if (oldThr > 0) {
// 如果原来的thredshold大于0则将容量设为原来的thredshold
// 在第一次带参数初始化时候会有这种情况
newCap = oldThr;
} else {
// 在默认无参数初始化会有这种情况
newCap = DEFAULT_INITIAL_CAPACITY;// 16
newThr = (int) (DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);// 0.75*16=12
}
if (newThr == 0) {
// 如果新 的容量 ==0
float ft = (float) newCap * loadFactor;// loadFactor 哈希加载因子 默认0.75,可在初始化时传入,16*0.75=12 可以放12个键值对
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float) MAXIMUM_CAPACITY ? (int) ft : Integer.MAX_VALUE);
}
threshold = newThr;// 将临界值设置为新临界值
@SuppressWarnings({ "rawtypes", "unchecked" })
// 扩容
Node<K, V>[] newTab = (Node<K, V>[]) new Node[newCap];
table = newTab;
// 如果原来的table有数据,则将数据复制到新的table中
if (oldTab != null) {
// 根据容量进行循环整个数组,将非空元素进行复制
for (int j = 0; j < oldCap; ++j) {
Node<K, V> e;
// 获取数组的第j个元素
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 如果链表只有一个,则进行直接赋值
if (e.next == null)
// e.hash & (newCap - 1) 确定元素存放位置
newTab[e.hash & (newCap - 1)] = e;
// 此处省略红黑树
else {
// 进行链表复制
// 方法比较特殊: 它并没有重新计算元素在数组中的位置
// 而是采用了 原始位置加原数组长度的方法计算得到位置
Node<K, V> loHead = null, loTail = null;
Node<K, V> hiHead = null, hiTail = null;
Node<K, V> next;
do {
next = e.next;
// 注意:不是(e.hash & (oldCap-1));而是(e.hash & oldCap)

// (e.hash & oldCap) 得到的是 元素的在数组中的位置是否需要移动,示例如下
// 示例1:
// e.hash=10 0000 1010
// oldCap=16 0001 0000
// & =0 0000 0000 比较高位的第一位 0
//结论:元素位置在扩容后数组中的位置没有发生改变

// 示例2:
// e.hash=17 0001 0001
// oldCap=16 0001 0000
// & =1 0001 0000 比较高位的第一位 1
//结论:元素位置在扩容后数组中的位置发生了改变,新的下标位置是原下标位置+原数组长度

// (e.hash & (oldCap-1)) 得到的是下标位置,示例如下
// e.hash=10 0000 1010
// oldCap-1=15 0000 1111
// & =10 0000 1010

// e.hash=17 0001 0001
// oldCap-1=15 0000 1111
// & =1 0000 0001

//新下标位置
// e.hash=17 0001 0001
// newCap-1=31 0001 1111 newCap=32
// & =17 0001 0001 1+oldCap = 1+16

//元素在重新计算hash之后,因为n变为2倍,那么n-1的mask范围在高位多1bit(红色),因此新的index就会发生这样的变化:
// 0000 0001->0001 0001

if ((e.hash & oldCap) == 0) {
// 如果原元素位置没有发生变化
if (loTail == null)
loHead = e;// 确定首元素
// 第一次进入时 e -> aa ; loHead-> aa
else
loTail.next = e;
//第二次进入时 loTail-> aa ; e -> bb ; loTail.next -> bb;而loHead和loTail是指向同一块内存的,所以loHead.next 地址为 bb
//第三次进入时 loTail-> bb ; e -> cc ; loTail.next 地址为 cc;loHead.next.next = cc
loTail = e;
// 第一次进入时 e -> aa ; loTail-> aa loTail指向了和 loHead相同的内存空间
// 第二次进入时 e -> bb ; loTail-> bb loTail指向了和 loTail.next(loHead.next)相同的内存空间 loTail=loTail.next
// 第三次进入时 e -> cc ; loTail-> cc loTail指向了和 loTail.next(loHead.next.next)相同的内存
} else {
//与上面同理

if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);//这一块就是 旧链表迁移新链表
//总结:1.8中 旧链表迁移新链表 链表元素相对位置没有变化; 实际是对对象的内存地址进行操作
//在1.7中 旧链表迁移新链表 如果在新表的数组索引位置相同,则链表元素会倒置
if (loTail != null) {
loTail.next = null;// 将链表的尾节点 的next 设置为空
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;// 将链表的尾节点 的next 设置为空
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}

二、线程安全

JDK-1.7 线程不安全

resize()导致线程不安全

1
2
3
4
5
6
7
transfer()函数逻辑
1. 对索引数组中的元素遍历
2. 对链表上的每一个节点遍历:用 next 取得要转移那个元素的下一个,将 e 转移到新 Hash 表的头部,使用头插法插入节点。
3. 循环2,直到链表节点全部转移
4. 循环1,直到所有索引数组全部转移

经过这几步,我们会发现转移的时候是逆序的。假如转移前链表顺序是1->2->3,那么转移后就会变成3->2->1。这时候就有点头绪了,死锁问题不就是因为1->2的同时2->1造成的吗?所以,HashMap 的死锁问题就出在这个transfer()函数上。
]]>
<h4 id="一:resize扩容"><a href="#一:resize扩容" class="headerlink" title="一:resize扩容"></a>一:resize扩容</h4><blockquote> <ol> <li>当前table Node数组赋给临时变
Mockito单元测试 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/09/05/Mockito单元测试/ 2018-09-05T07:42:29.000Z 2018-09-05T07:52:37.442Z Maven依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.5</version>
<scope>test</scope>
</dependency>

普通类mock

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;

public class DataHandlerTest {

@InjectMocks
DataHandler dataHandler = new DataHandler();

@Mock
protected HttpServletRequest request;

@Mock
protected HttpServletResponse response;

@Before
public void before() throws Exception {
MockitoAnnotations.initMocks(this);
}

@Test
public void testPrintString() throws Exception {
JsonResult result = new JsonResult();
Mockito.doNothing().doAnswer(new Answer() {

@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return null;
}
}).when(response).setHeader("Content-Type", "application/json");

String path = DataHandlerTest.class.getResource("/").getPath() + "dataHandler.txt";
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
PrintWriter writer = new PrintWriter(file);
Mockito.when(response.getWriter()).thenReturn(writer);
dataHandler.print(result);

if (file != null && file.exists()) {
file.delete();
}
}
}

静态类mock

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
@RunWith(PowerMockRunner.class)
@PrepareForTest(ThreadContext.class)
public class CartTest {


@InjectMocks
private Cart cart = new Cart();

@Mock
ThreadContext threadContext;

@Mock
protected HttpServletRequest request;

@Mock
protected HttpServletResponse response;

@Before
public void before() throws Exception {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(ThreadContext.class);

ThreadContext threadContext2 = new ThreadContext();
threadContext2.setLoginId("123");

//Mock当前用户信息 currentUser
Mockito.when(ThreadContext.getCurrentUser()).thenReturn(threadContext2);

//Mock response.setHeader方法
Mockito.doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return "called with arguments: " + args;
}
}).when(response).setHeader(Mockito.anyString(),Mockito.anyString());

}


/**
*
* Method: screen(Context context)
*
*/
@Test
public void test() throws Exception {
Map<String, String> map = Maps.newHashMap();
map.put("Login","test");
Context context = new MappedContext();

//Mock request中获取回调函数名的方法
Mockito.when(request.getParameter(Mockito.any(String.class))).thenReturn("callback");
cart.screen(context);

}
]]>
<h4 id="Maven依赖"><a href="#Maven依赖" class="headerlink" title="Maven依赖"></a>Maven依赖</h4><figure class="highlight plain"><table><tr><td class=
MySQL事务级别 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/09/05/MySQL事务级别/ 2018-09-05T07:41:29.000Z 2018-09-05T07:52:28.978Z 幻读:事务1读取数据时,事务2增加并提交,事务1再次读取数据时,可以看到事务B新增的数据。

不可重复读:事务1读取数据时,事务2修改并提交该数据,事务1再次读取事务时,可以看到事务B修改后的记录

脏读:事务1更新了记录,但没有提交,事务2读取了更新后的行,然后事务T1回滚,现在T2读取无效。

事务级别

  1. read uncommit:可能出现脏读,幻读,不可重复读
  2. read commit : 不允许出现脏读,可能出现幻读,不可重复读
  3. repeaable commit : 不会出现脏读、不可重复读,可能出现幻读
  4. seralizeable : 不会出现脏读,幻读,不可重复读

http://www.cnblogs.com/hustcat/archive/2009/10/28/1591648.html

]]>
<p>幻读:事务1读取数据时,事务2增加并提交,事务1再次读取数据时,可以看到事务B新增的数据。</p> <p>不可重复读:事务1读取数据时,事务2修改并提交该数据,事务1再次读取事务时,可以看到事务B修改后的记录</p> <p>脏读:事务1更新了记录,但没有提交,事务2读取了更
spring schema扩展 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/09/05/spring-schema扩展/ 2018-09-05T07:39:49.000Z 2018-09-05T07:52:18.692Z 介绍

Spring 2.5在2.0的基于Schema的Bean配置的基础之上,再增加了扩展XML配置的机制。通过该机制,我们可以编写自己的Schema,并根据自定义的Schema用自定的标签配置Bean。要使用的Spring的扩展XML配置机制,也比较简单,有以下4个步骤:

  1. 编写自定义Schema文件;
  2. 编写自定义NamespaceHandler;
  3. 编写解析BeanDefinition的parser
  4. 在Spring中注册上述组建

Maven依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
```

#### 一、编写schema文件

参考:[http://www.w3school.com.cn/schema/schema_elements_ref.asp](http://www.w3school.com.cn/schema/schema_elements_ref.asp) , 如下`people.xsd`文件:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.pomelo.com/schema/people"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:beans="http://www.springframework.org/schema/beans"
targetNamespace="http://www.pomelo.com/schema/people"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xsd:import namespace="http://www.springframework.org/schema/beans"/>

<xsd:element name="student">
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="beans:identifiedType">

<xsd:attribute name="name" type="xsd:string">
<xsd:annotation>
<xsd:documentation>姓名</xsd:documentation>
</xsd:annotation>
</xsd:attribute>

<xsd:attribute name="age" type="xsd:string">
<xsd:annotation>
<xsd:documentation>年龄</xsd:documentation>
</xsd:annotation>
</xsd:attribute>

</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
</xsd:schema>

二、编写自定义NamespaceHandler

1
2
3
4
5
6
7
8
9
10
11
12
package schema;

import org.springframework.beans.factory.xml.NamespaceHandlerSupport;

public class StudentNamespaceHandler extends NamespaceHandlerSupport {

@Override
public void init() {
registerBeanDefinitionParser("student", new StudentBeanDefinitionParser());
}

}

三、编写BeanDefinition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package schema;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

public class StudentBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {

protected Class getBeanClass(Element element) {
return Student.class;
}

protected void doParse(Element element, BeanDefinitionBuilder bean) {
String name = element.getAttribute("name");
bean.addPropertyValue("name", name);

String age = element.getAttribute("age");
if (StringUtils.hasText(age)) {
bean.addPropertyValue("age", Integer.valueOf(age));
}
}
}

实体类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package schema;

public class Student {

private String name;

private int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

}

四、注册schema组件

最后在META-INF目录下添加两个配置文件(spring.handler和spring.schema):

spring.handler配置如下:

1
http\://www.pomelo.com/schema/people=schema.StudentNamespaceHandler

spring.schema配置如下:

1
http\://www.pomelo.com/schema/people.xsd=META-INF/people.xsd

五、测试

新建applicationContext.xml放在clasapath下面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:people="http://www.pomelo.com/schema/people"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.pomelo.com/schema/people http://www.pomelo.com/schema/people.xsd">

<people:student id="student1" name="student1" age="18"/>

<people:student id="student2" name="student2" age="20" />


<bean id="student3" class="schema.Student">
<property name="name" value="student3"/>
<property name="age" value="23"/>
</bean>

</beans>

java调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package schema;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* Created by zhengyong on 17/3/3.
*/
public class SchemaTest {

public static void main(String[] args) {

ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
Student student1 = (Student) ctx.getBean("student1");
Student student2 = (Student) ctx.getBean("student2");
Student student3 = (Student) ctx.getBean("student3");

System.out.println("name: " + student1.getName() + " age :" + student1.getAge());
System.out.println("name: " + student2.getName() + " age :" + student2.getAge());
System.out.println("name: " + student3.getName() + " age :" + student3.getAge());
}
}

具体代码详见:https://github.com/zyongjava/pomelo/blob/master/src/main/resources/META-INF/people.xsd

]]>
<h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><blockquote> <p>Spring 2.5在2.0的基于Schema的Bean配置的基础之上,再增加了扩展XML配置的机制。通过该机制,
swagger自动生成API文档 https://blog.csdn.net/zhengyong15984285623?viewmode=contents/2018/09/05/swagger自动生成API文档/ 2018-09-05T07:38:43.000Z 2018-09-05T07:39:09.913Z 一、pom.xml配置
1
2
3
4
5
6
7
8
9
10
11
<!--swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>

二、spring boot配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package cn.pomelo.web.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
* swagger自动生成API文档 (http://127.0.0.1:8080/swagger-ui.html)
*/
@EnableSwagger2
@Configuration
public class SwaggerConfig {

//是否开启swagger,正式环境一般是需要关闭的,可根据springboot的多环境配置进行设置
@Value(value = "${swagger.enabled}")
Boolean swaggerEnabled;

@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
// 是否开启
.enable(swaggerEnabled).select()
// 扫描的路径包
.apis(RequestHandlerSelectors.basePackage("cn.pomelo.web.controller"))
// 指定路径处理PathSelectors.any()代表所有的路径
.paths(PathSelectors.any()).build().pathMapping("/");
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot-Swagger2集成和使用-demo示例")
.description("spring boot swagger restful api document")
// 作者信息
.contact(new Contact("yong.zheng", "https://blog.csdn.net/zhengyong15984285623?viewmode=contents", "zyongjava@163.com"))
.version("1.0.0")
.build();
}
}

三、swagger-ui.html配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
* MVC配置
*
*/
@Configuration
public class CustomMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");

registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");

}
}

四、注解说明

常用到的注解:

1
2
3
4
5
6
7
8
@Api
@ApiModel
@ApiModelProperty
@ApiOperation
@ApiParam
@ApiResponse
@ApiResponses
@ResponseHeader

地址:https://www.cnblogs.com/hyl8218/p/8520994.html

]]>
<h4 id="一、pom-xml配置"><a href="#一、pom-xml配置" class="headerlink" title="一、pom.xml配置"></a>一、pom.xml配置</h4><figure class="highlight plain"><tabl