Browse Source

spring admin

yufeng0528 4 years ago
parent
commit
d8fa23720f

+ 1 - 0
pom.xml

@@ -17,6 +17,7 @@
17 17
         <module>spring5-admin</module>
18 18
         <module>spring5-order</module>
19 19
         <module>spring5-common</module>
20
+        <module>spring5-monitor</module>
20 21
     </modules>
21 22
 
22 23
 	<properties>

+ 44 - 39
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/intercept/ServiceAuthRestInterceptor.java

@@ -38,45 +38,50 @@ public class ServiceAuthRestInterceptor extends HandlerInterceptorAdapter {
38 38
 //			return super.preHandle(request, response, handler);
39 39
 //		}
40 40
 		
41
-      // 配置该注解,说明不进行服务拦截
42
-      IgnoreClientToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreClientToken.class);
43
-      if (annotation == null) {
44
-          annotation = handlerMethod.getMethodAnnotation(IgnoreClientToken.class);
45
-      }
46
-      if(annotation != null) {
47
-          return super.preHandle(request, response, handler);
48
-      }
49
-
50
-		String clientToken = request.getHeader("x-auth-client-" + applicationName);
51
-		String client = request.getHeader("x-auth-client");
52
-		
53
-		try {
54
-			if (StringUtils.isEmpty(clientToken)) {
55
-				String clientName = JwtUtils.getUsername(client);
56
-				// authServer校验 客户端是否合法&能否有权限访问
57
-				if (Boolean.TRUE.equals(clientAuthProvider.verify(applicationName, clientName.split("\\.")[0], clientName.split("\\.")[1]))) {
58
-					// 给该客户端签名
59
-					String signToken = JwtUtils.sign(JwtUtils.generateSalt(), "xP3La8IhZjl4fmWXD.AYVH5tor5bn-Rr", 3600*12);
60
-					response.addHeader("x-auth-client-response", signToken);
61
-					
62
-					log.info("auth-server verify success, sign with {}", signToken);
63
-					
64
-					return super.preHandle(request, response, handler);
65
-				}
66
-				
67
-			} else {
68
-				// jwt校验
69
-				if (!JwtUtils.isTokenExpired(clientToken) && JwtUtils.verifyToken(clientToken, "xP3La8IhZjl4fmWXD.AYVH5tor5bn-Rr") != null) {
70
-					log.info("local service jwt verify success");
71
-					return super.preHandle(request, response, handler);
72
-				}
73
-			}
74
-			
75
-		} catch (Exception e) {
76
-			log.error(e.getMessage(), e);
77
-			throw new ClientForbiddenException("Client verfy error");
41
+		// 配置该注解,说明不进行服务拦截
42
+		IgnoreClientToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreClientToken.class);
43
+		if (annotation == null) {
44
+			annotation = handlerMethod.getMethodAnnotation(IgnoreClientToken.class);
45
+		}
46
+		if (annotation != null) {
47
+			return super.preHandle(request, response, handler);
78 48
 		}
79
-      
80
-      throw new ClientForbiddenException("Client is Forbidden!");
49
+
50
+		return super.preHandle(request, response, handler);
51
+
52
+//		String clientToken = request.getHeader("x-auth-client-" + applicationName);
53
+//		String client = request.getHeader("x-auth-client");
54
+//
55
+//		try {
56
+//			if (StringUtils.isEmpty(clientToken)) {
57
+//				String clientName = JwtUtils.getUsername(client);
58
+//				// authServer校验 客户端是否合法&能否有权限访问
59
+//				if (Boolean.TRUE.equals(clientAuthProvider.verify(applicationName, clientName.split("\\.")[0],
60
+//						clientName.split("\\.")[1]))) {
61
+//					// 给该客户端签名
62
+//					String signToken = JwtUtils.sign(JwtUtils.generateSalt(), "xP3La8IhZjl4fmWXD.AYVH5tor5bn-Rr",
63
+//							3600 * 12);
64
+//					response.addHeader("x-auth-client-response", signToken);
65
+//
66
+//					log.info("auth-server verify success, sign with {}", signToken);
67
+//
68
+//					return super.preHandle(request, response, handler);
69
+//				}
70
+//
71
+//			} else {
72
+//				// jwt校验
73
+//				if (!JwtUtils.isTokenExpired(clientToken)
74
+//						&& JwtUtils.verifyToken(clientToken, "xP3La8IhZjl4fmWXD.AYVH5tor5bn-Rr") != null) {
75
+//					log.info("local service jwt verify success");
76
+//					return super.preHandle(request, response, handler);
77
+//				}
78
+//			}
79
+//
80
+//		} catch (Exception e) {
81
+//			log.error(e.getMessage(), e);
82
+//			throw new ClientForbiddenException("Client verfy error");
83
+//		}
84
+//
85
+//		throw new ClientForbiddenException("Client is Forbidden!");
81 86
   }
82 87
 }

+ 16 - 0
spring5-monitor/.gitignore

@@ -0,0 +1,16 @@
1
+target/
2
+logs/
3
+
4
+### STS ###
5
+.apt_generated
6
+.classpath
7
+.factorypath
8
+.project
9
+.settings
10
+.springBeans
11
+
12
+### IntelliJ IDEA ###
13
+.idea
14
+*.iws
15
+*.iml
16
+*.ipr

+ 61 - 0
spring5-monitor/pom.xml

@@ -0,0 +1,61 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4
+    <modelVersion>4.0.0</modelVersion>
5
+
6
+    <artifactId>spring5-monitor</artifactId>
7
+    <packaging>jar</packaging>
8
+
9
+    <name>admin</name>
10
+
11
+    <parent>
12
+        <groupId>com.yaozhitech</groupId>
13
+        <artifactId>spring5</artifactId>
14
+        <version>0.1.0</version>
15
+    </parent>
16
+
17
+    <properties>
18
+        <admin-server.version>2.1.6</admin-server.version>
19
+    </properties>
20
+
21
+    <dependencies>
22
+        <dependency>
23
+            <groupId>org.springframework.boot</groupId>
24
+            <artifactId>spring-boot-starter-web</artifactId>
25
+        </dependency>
26
+        <dependency>
27
+            <groupId>de.codecentric</groupId>
28
+            <artifactId>spring-boot-admin-starter-server</artifactId>
29
+            <version>${admin-server.version}</version>
30
+        </dependency>
31
+        <dependency>
32
+            <groupId>org.springframework.boot</groupId>
33
+            <artifactId>spring-boot-starter-security</artifactId>
34
+        </dependency>
35
+    </dependencies>
36
+
37
+    <build>
38
+        <plugins>
39
+            <!--docker镜像build插件-->
40
+            <plugin>
41
+                <groupId>com.spotify</groupId>
42
+                <artifactId>docker-maven-plugin</artifactId>
43
+                <version>1.2.0</version>
44
+                <configuration>
45
+                    <!-- 注意imageName一定要是符合正则[a-z0-9-_.]的,否则构建不会成功 -->
46
+                    <imageName>cike/${project.artifactId}</imageName>
47
+                    <dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
48
+                    <rm>true</rm>
49
+                    <resources>
50
+                        <resource>
51
+                            <targetPath>/</targetPath>
52
+                            <directory>${project.build.directory}</directory>
53
+                            <include>${project.build.finalName}.jar</include>
54
+                        </resource>
55
+                    </resources>
56
+                </configuration>
57
+            </plugin>
58
+        </plugins>
59
+    </build>
60
+
61
+</project>

+ 154 - 0
spring5-monitor/readme.md

@@ -0,0 +1,154 @@
1
+
2
+快速构建spring-cloud + sleuth + rabbit + zipkin + es + kibana + grafana日志跟踪平台
3
+-------------
4
+
5
+## 简介
6
+
7
+ ### Spring-Cloud-Sleuth
8
+  
9
+ Spring-Cloud-Sleuth是Spring Cloud的组成部分之一,为SpringCloud应用实现了一种分布式追踪解决方案,其兼容了Zipkin, HTrace和log-based追踪
10
+ 
11
+ * 术语(Terminology)
12
+ 
13
+ **Span:** 基本工作单元,例如,在一个新建的span中发送一个RPC等同于发送一个回应请求给RPC,span通过一个64位ID唯一标识,trace以另一个64位ID表示,span还有其他数据信息,比如摘要、时间戳事件、关键值注释(tags)、span的ID、以及进度ID(通常是IP地址)
14
+ 
15
+ span在不断的启动和停止,同时记录了时间信息,当你创建了一个span,你必须在未来的某个时刻停止它。
16
+ 
17
+ **Trace:** 一系列spans组成的一个树状结构,例如,如果你正在跑一个分布式大数据工程,你可能需要创建一个trace。
18
+ 
19
+ **Annotation:** 用来及时记录一个事件的存在,一些核心annotations用来定义一个请求的开始和结束
20
+ 
21
+ cs - Client Sent -客户端发起一个请求,这个annotion描述了这个span的开始
22
+ sr - Server Received -服务端获得请求并准备开始处理它,如果将其sr减去cs时间戳便可得到网络延迟
23
+ ss - Server Sent -注解表明请求处理的完成(当请求返回客户端),如果ss减去sr时间戳便可得到服务端需要的处理请求时间
24
+ cr - Client Received -表明span的结束,客户端成功接收到服务端的回复,如果cr减去cs时间戳便可得到客户端从服务端获取回复的所有所需时间
25
+ 
26
+ 将Span和Trace在一个系统中使用Zipkin注解的过程图形化:
27
+ 
28
+ ![图片](../docs/sleuth.png)
29
+ 
30
+ ### Rabbitmq: 消息队列,主要用于传输日志
31
+ 
32
+ 
33
+ ### Zipkin: 服务调用链路追踪系统,聚合各业务系统调用延迟数据,达到链路调用监控与跟踪。
34
+
35
+ 服务调用链路
36
+ ![图片](../docs/zipkin-server.png)
37
+ 
38
+ 服务调用链路详情
39
+ ![图片](../docs/zipkin-detail.png)
40
+ 
41
+ 服务间的调用关系
42
+ ![图片](../docs/zipkin-dependencies.png)
43
+
44
+ ### ES + Kibana提供搜索、查看和与存储在 Elasticsearch 索引中的数据进行交互的功能。开发者或运维人员可以轻松地执行高级数据分析,并在各种图表、表格和地图中可视化数据。
45
+ 
46
+ ![图片](../docs/kibana.png)
47
+
48
+ ### Grafana可视化图表监控工具
49
+ 
50
+  ![图片](../docs/grafana.png)
51
+  
52
+
53
+## zipkin-server搭建与使用
54
+
55
+docker-compose
56
+
57
+```yaml
58
+version: '3'
59
+services:
60
+  rabbitmq:
61
+    image: rabbitmq:alpine
62
+    container_name: sc-rabbitmq
63
+    restart: always
64
+    volumes:
65
+      - ./data/rabbitmq:/var/lib/rabbitmq
66
+    networks:
67
+      - sc-net
68
+    ports:
69
+      - 5672:5672
70
+      
71
+  zipkin-server:
72
+    image: openzipkin/zipkin
73
+    container_name: sc-zipkin-server
74
+    restart: always
75
+    volumes:
76
+      - ./data/logs/zipkin-server:/logs
77
+    networks:
78
+      - sc-net
79
+    ports:
80
+      - 9411:9411
81
+    environment:
82
+      - RABBIT_ADDRESSES=rabbitmq:5672
83
+      - RABBIT_MQ_PORT=5672
84
+      - RABBIT_PASSWORD=guest
85
+      - RABBIT_USER=guest
86
+    depends_on:
87
+      - rabbitmq
88
+
89
+```
90
+## 搭建ES + Grafana
91
+```yaml
92
+version: '3'
93
+services:
94
+  elasticsearch:
95
+    image: elasticsearch:alpine
96
+    container_name: sc-elasticsearch
97
+    restart: always
98
+    volumes:
99
+      - ./data/elasticsearch/logs:/var/logs/elasticsearch
100
+    networks:
101
+      - sc-net
102
+    ports:
103
+      - 9200:9200
104
+
105
+  kibana:
106
+    image: kibana
107
+    container_name: sc-kibana
108
+    restart: always
109
+    volumes:
110
+      - ./data/kibana/logs:/var/logs/kibana
111
+    networks:
112
+      - sc-net
113
+    ports:
114
+      - 5601:5601
115
+    environment:
116
+      - ELASTICSEARCH_URL=http://elasticsearch:9200
117
+    depends_on:
118
+      - elasticsearch
119
+
120
+  grafana:
121
+    image: grafana/grafana
122
+    container_name: sc-grafana
123
+    restart: always
124
+    volumes:
125
+      - ./data/grafana/logs:/var/logs/grafana
126
+    networks:
127
+      - sc-net
128
+    ports:
129
+      - 3000:3000
130
+```
131
+
132
+## 测试
133
+
134
+### 启动服务
135
+
136
+将以上docker-compose脚本保存为ocker-compose.yml,并在当时目录下执行`docker-compose up`
137
+
138
+### spring-cloud集成
139
+
140
+请参考:https://github.com/zhoutaoo/SpringCloud例子
141
+
142
+应用集成开发好后,请求应用的接口
143
+
144
+### 查看日志
145
+
146
+zipkin访问地址:http://localhost:9411,可以看到请求的耗时与路径
147
+
148
+kibana访问地址:http://localhost:5601,可以看到请求打印的日志
149
+
150
+grafana访问地址:http://localhost:3000,可以新增es数据源,出可视化的图表和监控
151
+
152
+
153
+
154
+

+ 4 - 0
spring5-monitor/src/main/docker/Dockerfile

@@ -0,0 +1,4 @@
1
+FROM java:alpine
2
+VOLUME /tmp
3
+ADD admin-0.0.1-SNAPSHOT.jar app.jar
4
+ENTRYPOINT ["java","-jar","/app.jar"]

+ 15 - 0
spring5-monitor/src/main/java/com/springboot/admin/AdminApplication.java

@@ -0,0 +1,15 @@
1
+package com.springboot.admin;
2
+
3
+import de.codecentric.boot.admin.server.config.EnableAdminServer;
4
+import org.springframework.boot.SpringApplication;
5
+import org.springframework.boot.autoconfigure.SpringBootApplication;
6
+import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
7
+
8
+@SpringBootApplication
9
+@EnableDiscoveryClient
10
+@EnableAdminServer
11
+public class AdminApplication {
12
+    public static void main(String[] args) {
13
+        SpringApplication.run(AdminApplication.class, args);
14
+    }
15
+}

+ 37 - 0
spring5-monitor/src/main/java/com/springboot/admin/SecurityConfig.java

@@ -0,0 +1,37 @@
1
+package com.springboot.admin;
2
+
3
+import de.codecentric.boot.admin.server.config.AdminServerProperties;
4
+import org.springframework.context.annotation.Configuration;
5
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
6
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
7
+import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
8
+
9
+@Configuration
10
+public class SecurityConfig extends WebSecurityConfigurerAdapter {
11
+    private final String adminContextPath;
12
+
13
+    public SecurityConfig(AdminServerProperties adminServerProperties) {
14
+        this.adminContextPath = adminServerProperties.getContextPath();
15
+    }
16
+
17
+    @Override
18
+    protected void configure(HttpSecurity http) throws Exception {
19
+        // @formatter:off
20
+        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
21
+        successHandler.setTargetUrlParameter("redirectTo");
22
+
23
+        http.authorizeRequests()
24
+                .antMatchers(adminContextPath + "/assets/**").permitAll()
25
+                .antMatchers(adminContextPath + "/actuator/**").permitAll()
26
+                .antMatchers(adminContextPath + "/login").permitAll()
27
+                .anyRequest().authenticated()
28
+                .and()
29
+                .formLogin().loginPage(adminContextPath + "/login")
30
+                .successHandler(successHandler).and()
31
+                .logout().logoutUrl(adminContextPath + "/logout")
32
+                .and()
33
+                .httpBasic().and()
34
+                .csrf().disable();
35
+        // @formatter:on
36
+    }
37
+}

+ 38 - 0
spring5-monitor/src/main/resources/application.yml

@@ -0,0 +1,38 @@
1
+spring:
2
+  rabbitmq:
3
+    host: ${RABBIT_MQ_HOST:localhost}
4
+    port: ${RABBIT_MQ_PORT:5672}
5
+    username: ${RABBIT_MQ_USERNAME:guest}
6
+    password: ${RABBIT_MQ_PASSWORD:guest}
7
+  redis:
8
+    host: ${REDIS_HOST:localhost}
9
+    port: ${REDIS_PORT:6379}
10
+    ##password: ${REDIS_PASSWORD:}
11
+  #spring boot admin的登陆账号和密码配置
12
+  security:
13
+    user:
14
+      name: admin
15
+      password: 123456
16
+  #通过rabbit MQ将日志发给zipkin
17
+  zipkin:
18
+    enabled: true
19
+    sender:
20
+      type: rabbit
21
+  sleuth:
22
+    sampler:
23
+      probability: 1.0
24
+
25
+management:
26
+  endpoints:
27
+    web:
28
+      exposure:
29
+        include: '*'
30
+#日志相关配置
31
+logging:
32
+  level:
33
+    org.springframework.security: DEBUG
34
+  path: logs/
35
+  file:
36
+    max-size: 1GB
37
+
38
+

+ 12 - 0
spring5-monitor/src/main/resources/bootstrap.yml

@@ -0,0 +1,12 @@
1
+server:
2
+  port: ${SERVER_PORT:8022}
3
+spring:
4
+  application:
5
+    name: admin
6
+  cloud:
7
+    nacos:
8
+      discovery:
9
+        server-addr: ${REGISTER_HOST:192.168.99.100}:${REGISTER_PORT:8848}
10
+      config:
11
+        server-addr: ${REGISTER_HOST:192.168.99.100}:${REGISTER_PORT:8848}
12
+        file-extension: yml

+ 16 - 0
spring5-monitor/src/test/java/com/springboot/admin/ConsumerApplicationTests.java

@@ -0,0 +1,16 @@
1
+package com.springboot.admin;
2
+
3
+import org.junit.Test;
4
+import org.junit.runner.RunWith;
5
+import org.springframework.boot.test.context.SpringBootTest;
6
+import org.springframework.test.context.junit4.SpringRunner;
7
+
8
+@RunWith(SpringRunner.class)
9
+@SpringBootTest
10
+public class ConsumerApplicationTests {
11
+
12
+    @Test
13
+    public void contextLoads() {
14
+    }
15
+
16
+}

+ 11 - 0
spring5-order/pom.xml

@@ -39,6 +39,17 @@
39 39
             <artifactId>feign-okhttp</artifactId>
40 40
         </dependency>
41 41
         
42
+        <!-- admin -->
43
+        <dependency>
44
+            <groupId>de.codecentric</groupId>
45
+            <artifactId>spring-boot-admin-starter-client</artifactId>
46
+            <version>2.1.6</version>
47
+        </dependency>
48
+<!--         <dependency> -->
49
+<!-- 		    <groupId>org.springframework.boot</groupId> -->
50
+<!-- 		    <artifactId>spring-boot-starter-security</artifactId> -->
51
+<!-- 		</dependency> -->
52
+        
42 53
 <!--         <dependency> -->
43 54
 <!--             <groupId>org.springframework.cloud</groupId> -->
44 55
 <!--             <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> -->

+ 11 - 1
spring5-order/src/main/resources/application.yml

@@ -13,10 +13,20 @@ spring:
13 13
     port: 6280
14 14
     password: bbztx123456
15 15
     timeout: 5000
16
+  boot:
17
+    admin:
18
+      client:
19
+        url:
20
+        - http://127.0.0.1:8022
21
+        username: admin
22
+        password: 123456
23
+          
16 24
   
17 25
 password:
18 26
   salt: k12829WhsvnEV$#03b2n          
19 27
   
20 28
 auth:
21 29
   client:
22
-    secret: qx4MXVR9SJm31q2C
30
+    secret: qx4MXVR9SJm31q2C
31
+    
32
+