程序员果果的博客

  • 首页

  • 标签

  • 分类

  • 归档

SpringBoot 自定义 starter

发表于 2019-03-08 | 分类于 SpringBoot

一、简介

SpringBoot 最强大的功能就是把我们常用的场景抽取成了一个个starter(场景启动器),我们通过引入SpringBoot 为我提供的这些场景启动器,我们再进行少量的配置就能使用相应的功能。即使是这样,SpringBoot也不能囊括我们所有的使用场景,往往我们需要自定义starter,来简化我们对SpringBoot的使用。

二、如何自定义starter

1.实例

如何编写自动配置 ?

我们参照@WebMvcAutoConfiguration为例,我们看看需要准备哪些东西,下面是WebMvcAutoConfiguration的部分代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {

@Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})
@EnableConfigurationProperties({WebMvcProperties.class, ResourceProperties.class})
public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter {

@Bean
@ConditionalOnBean({View.class})
@ConditionalOnMissingBean
public BeanNameViewResolver beanNameViewResolver() {
BeanNameViewResolver resolver = new BeanNameViewResolver();
resolver.setOrder(2147483637);
return resolver;
}
}
}

我们可以抽取到我们自定义starter时,同样需要的一些配置。

1
2
3
4
5
6
7
8
9
10
11
@Configuration  //指定这个类是一个配置类
@ConditionalOnXXX //指定条件成立的情况下自动配置类生效
@AutoConfigureOrder //指定自动配置类的顺序
@Bean //向容器中添加组件
@ConfigurationProperties //结合相关xxxProperties来绑定相关的配置
@EnableConfigurationProperties //让xxxProperties生效加入到容器中

自动配置类要能加载需要将自动配置类,配置在META-INF/spring.factories中
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\

模式

我们参照 spring-boot-starter 我们发现其中没有代码:

我们在看它的pom中的依赖中有个 springboot-starter

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

我们再看看 spring-boot-starter 有个 spring-boot-autoconfigure

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>

关于web的一些自动配置都写在了这里 ,所以我们有以下总结:

1
2
3
启动器starter只是用来做依赖管理
需要专门写一个类似spring-boot-autoconfigure的配置模块
用的时候只需要引入启动器starter,就可以使用自动配置了

命名规范

官方命名空间

  • 前缀:spring-boot-starter-
  • 模式:spring-boot-starter-模块名
  • 举例:spring-boot-starter-web、spring-boot-starter-jdbc

自定义命名空间

  • 后缀:-spring-boot-starter
  • 模式:模块-spring-boot-starter
  • 举例:mybatis-spring-boot-starter

三、自定义starter实例

我们需要先创建两个工程 hello-spring-boot-starter 和 hello-spring-boot-starter-autoconfigurer

1. hello-spring-boot-starter

1.pom.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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.gf</groupId>
<artifactId>hello-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>hello-spring-boot-starter</name>

<!-- 启动器 -->
<dependencies>
<!-- 引入自动配置模块 -->
<dependency>
<groupId>com.gf</groupId>
<artifactId>hello-spring-boot-starter-autoconfigurer</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>


</project>

同时删除 启动类、resources下的文件,test文件。

2. hello-spring-boot-starter-autoconfigurer

1. pom.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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.gf</groupId>
<artifactId>hello-spring-boot-starter-autoconfigurer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>hello-spring-boot-starter-autoconfigurer</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<!-- 引入spring-boot-starter,所有starter的基本配合 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

</dependencies>


</project>

2. HelloProperties

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
package com.gf.service;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "gf.hello")
public class HelloProperties {

private String prefix;
private String suffix;

public String getPrefix() {
return prefix;
}

public void setPrefix(String prefix) {
this.prefix = prefix;
}

public String getSuffix() {
return suffix;
}

public void setSuffix(String suffix) {
this.suffix = suffix;
}

}

3. HelloService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.gf.service;


public class HelloService {

HelloProperties helloProperties;

public HelloProperties getHelloProperties() {
return helloProperties;
}

public void setHelloProperties(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}

public String sayHello(String name ) {
return helloProperties.getPrefix()+ "-" + name + helloProperties.getSuffix();
}
}

4. HelloServiceAutoConfiguration

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 com.gf.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnWebApplication //web应该生效
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {

@Autowired
HelloProperties helloProperties;

@Bean
public HelloService helloService() {
HelloService service = new HelloService();
service.setHelloProperties( helloProperties );
return service;
}


}

5. spring.factories

在 resources 下创建文件夹 META-INF 并在 META-INF 下创建文件 spring.factories ,内容如下:

1
2
3
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.gf.service.HelloServiceAutoConfiguration

到这儿,我们的配置自定义的starter就写完了 ,我们把 hello-spring-boot-starter-autoconfigurer、hello-spring-boot-starter 安装成本地jar包。

三、测试自定义starter

我们创建个项目 hello-spring-boot-starter-test,来测试系我们写的stater。

1. pom.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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.gf</groupId>
<artifactId>hello-spring-boot-starter-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>hello-spring-boot-starter-test</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 引入自定义starter -->
<dependency>
<groupId>com.gf</groupId>
<artifactId>hello-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


</project>

2. HelloController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.gf.controller;

import com.gf.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@Autowired
HelloService helloService;

@GetMapping("/hello/{name}")
public String hello(@PathVariable(value = "name") String name) {
return helloService.sayHello( name + " , " );
}

}

3. application.properties

1
2
gf.hello.prefix = hi
gf.hello.suffix = what's up man ?

我运行项目访问 http://127.0.0.1:8080/hello/zhangsan,结果如下:

1
hi-zhangsan , what's up man ?

源码下载: https://github.com/gf-huanchupk/SpringBootLearning

SpringBoot admin 2.0 详解

发表于 2019-03-08 | 分类于 SpringBoot

一、什么是Spring Boot Admin ?

Spring Boot Admin是一个开源社区项目,用于管理和监控SpringBoot应用程序。 应用程序作为Spring Boot Admin Client向为Spring Boot Admin Server注册(通过HTTP)或使用SpringCloud注册中心(例如Eureka,Consul)发现。 UI是的Vue.js应用程序,展示Spring Boot Admin Client的Actuator端点上的一些监控。服务端采用Spring WebFlux + Netty的方式。Spring Boot Admin为注册的应用程序提供以下功能:

  • 显示健康状况
  • 显示详细信息,例如
    • JVM和内存指标
    • micrometer.io指标
    • 数据源指标
    • 缓存指标
  • 显示构建信息编号
  • 关注并下载日志文件
  • 查看jvm system-和environment-properties
  • 查看Spring Boot配置属性
  • 支持Spring Cloud的postable / env-和/ refresh-endpoint
  • 轻松的日志级管理
  • 与JMX-beans交互
  • 查看线程转储
  • 查看http-traces
  • 查看auditevents
  • 查看http-endpoints
  • 查看计划任务
  • 查看和删除活动会话(使用spring-session)
  • 查看Flyway / Liquibase数据库迁移
  • 下载heapdump
  • 状态变更通知(通过电子邮件,Slack,Hipchat,……)
  • 状态更改的事件日志(非持久性)

二、入门

1. 创建 Spring Boot Admin Server

pom.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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gf</groupId>
<artifactId>admin-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>admin-server</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
<spring-boot-admin.version>2.1.0</spring-boot-admin.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-dependencies</artifactId>
<version>${spring-boot-admin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

application.yml

1
2
3
4
5
spring:
application:
name: admin-server
server:
port: 8769

启动类 AdminServerApplication

启动类加上@EnableAdminServer注解,开启AdminServer的功能:

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@EnableAdminServer
public class AdminServerApplication {

public static void main(String[] args) {
SpringApplication.run( AdminServerApplication.class, args );
}

}

2. 创建 Spring Boot Admin Client

pom.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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gf</groupId>
<artifactId>admin-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>admin-client</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
<spring-boot-admin.version>2.1.0</spring-boot-admin.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-dependencies</artifactId>
<version>${spring-boot-admin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

application.yml

  • spring.boot.admin.client.url:要注册的Spring Boot Admin Server的URL。
  • management.endpoints.web.exposure.include:与Spring Boot 2一样,默认情况下,大多数actuator的端口都不会通过http公开,* 代表公开所有这些端点。对于生产环境,应该仔细选择要公开的端点。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
spring:
application:
name: admin-client
boot:
admin:
client:
url: http://localhost:8769
server:
port: 8768

management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: ALWAYS

启动类 AdminClientApplication

1
2
3
4
5
6
7
8
@SpringBootApplication
public class AdminClientApplication {

public static void main(String[] args) {
SpringApplication.run( AdminClientApplication.class, args );
}

}

启动两个工程,在浏览器上输入localhost:8769 ,浏览器显示的界面如下:

查看wallboard:

点击wallboard,可以查看admin-client具体的信息,比如内存状态信息:

查看spring bean的情况:

查看应用程序运行状况,信息和详细:

还有很多监控信息,多点一点就知道。

三、集成 Eureka

1. 创建 sc-eureka-server

这是一个 eureka-server 注册中心。

pom.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gf</groupId>
<artifactId>sc-admin-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sc-admin-server</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
<spring-boot-admin.version>2.1.0</spring-boot-admin.version>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-dependencies</artifactId>
<version>${spring-boot-admin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
spring:
application:
name: sc-eureka-server
server:
port: 8761
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
register-with-eureka: false
fetch-registry: false
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: ALWAYS

启动类 ScEurekaServerApplication

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@EnableEurekaServer
public class ScEurekaServerApplication {

public static void main(String[] args) {
SpringApplication.run( ScEurekaServerApplication.class, args );
}

}

2. 创建 sc-admin-server

这是一个 Spring Boot Admin Server端。

pom.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gf</groupId>
<artifactId>sc-admin-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sc-admin-server</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
<spring-boot-admin.version>2.1.0</spring-boot-admin.version>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-dependencies</artifactId>
<version>${spring-boot-admin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
spring:
application:
name: admin-server
server:
port: 8769
eureka:
client:
registryFetchIntervalSeconds: 5
service-url:
defaultZone: ${EUREKA_SERVICE_URL:http://localhost:8761}/eureka/
instance:
leaseRenewalIntervalInSeconds: 10
health-check-url-path: /actuator/health

management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: ALWAYS

启动类 ScAdminServerApplication

1
2
3
4
5
6
7
8
9
10
@SpringBootApplication
@EnableAdminServer
@EnableDiscoveryClient
public class ScAdminServerApplication {

public static void main(String[] args) {
SpringApplication.run( ScAdminServerApplication.class, args );
}

}

3. 创建 sc-admin-client

这是一个 Spring Boot Admin client 端。

pom.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
71
72
73
74
75
76
77
78
79
80
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gf</groupId>
<artifactId>sc-admin-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sc-admin-client</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
<spring-boot-admin.version>2.1.0</spring-boot-admin.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-dependencies</artifactId>
<version>${spring-boot-admin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
spring:
application:
name: sc-admin-client
eureka:
instance:
leaseRenewalIntervalInSeconds: 10
health-check-url-path: /actuator/health

client:
registryFetchIntervalSeconds: 5
service-url:
defaultZone: ${EUREKA_SERVICE_URL:http://localhost:8761}/eureka/
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: ALWAYS
server:
port: 8762

启动类 ScAdminClientApplication

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@EnableDiscoveryClient
public class ScAdminClientApplication {

public static void main(String[] args) {
SpringApplication.run( ScAdminClientApplication.class, args );
}

}

启动三个工程,访问localhost:8769,出现如下界面:

admin 会自己拉取 Eureka 上注册的 app 信息,主动去注册。这也是唯一区别之前入门中手动注册的地方,就是 client 端不需要 admin-client 的依赖,也不需要配置 admin 地址了,一切全部由 admin-server 自己实现。这样的设计对环境变化很友好,不用改了admin-server后去改所有app 的配置了。

四、集成 Spring Security

Web应用程序中的身份验证和授权有多种方法,因此Spring Boot Admin不提供默认方法。默认情况下,spring-boot-admin-server-ui提供登录页面和注销按钮。我们结合 Spring Security 实现需要用户名和密码登录的安全认证。

sc-admin-server工程的pom文件需要增加以下的依赖:

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

在 sc-admin-server工的配置文件 application.yml 中配置 spring security 的用户名和密码,这时需要在服务注册时带上 metadata-map 的信息,如下:

1
2
3
4
5
6
7
8
9
10
11
spring:
security:
user:
name: "admin"
password: "admin"

eureka:
instance:
metadata-map:
user.name: ${spring.security.user.name}
user.password: ${spring.security.user.password}

@EnableWebSecurity注解以及WebSecurityConfigurerAdapter一起配合提供基于web的security。继承了WebSecurityConfigurerAdapter之后,再加上几行代码,我们就能实现要求用户在进入应用的任何URL之前都进行验证的功能,写一个配置类SecuritySecureConfig继承WebSecurityConfigurerAdapter,配置如下:

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
@Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {

private final String adminContextPath;

public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
this.adminContextPath = adminServerProperties.getContextPath();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(adminContextPath + "/");

http.authorizeRequests()
//授予对所有静态资产和登录页面的公共访问权限。
.antMatchers(adminContextPath + "/assets/**").permitAll()
.antMatchers(adminContextPath + "/login").permitAll()
//必须对每个其他请求进行身份验证
.anyRequest().authenticated()
.and()
//配置登录和注销
.formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
.logout().logoutUrl(adminContextPath + "/logout").and()
//启用HTTP-Basic支持。这是Spring Boot Admin Client注册所必需的
.httpBasic().and();
// @formatter:on
}
}

重新访问 http://localhost:8769/ 会出现登录界面,密码是 配置文件中配置好的,账号 admin 密码 admin,界面如下:

五、通知

1. 邮件通知

在 Spring Boot Admin 中 当注册的应用程序状态更改为DOWN、UNKNOWN、OFFLINE 都可以指定触发通知,下面讲解配置邮件通知。

在sc-admin-server工程pom文件,加上mail的依赖,如下:

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

在配置文件application.yml文件中,配置收发邮件的配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
spring:
mail:
host: smtp.163.com
username: xxxx@163.com
password: xxxx
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
boot:
admin:
notify:
mail:
from: xxxx@163.com
to: xxxx@qq.com

配置后,重启sc-admin-server工程,之后若出现注册的客户端的状态从 UP 变为 OFFLINE 或其他状态,服务端就会自动将电子邮件发送到上面配置的收件地址。

注意 : 配置了邮件通知后,会出现 反复通知 service offline / up。这个问题的原因在于 查询应用程序的状态和信息超时,下面给出两种解决方案:

1
2
3
4
5
6
7
8
9
10
#方法一:增加超时时间(单位:ms)

spring.boot.admin.monitor.read-timeout=20000

#方法二:关闭闭未使用或不重要的检查点

management.health.db.enabled=false
management.health.mail.enabled=false
management.health.redis.enabled=false
management.health.mongo.enabled=false

2. 自定义通知

可以通过添加实现Notifier接口的Spring Beans来添加您自己的通知程序,最好通过扩展 AbstractEventNotifier或AbstractStatusChangeNotifier。在sc-admin-server工程中编写一个自定义的通知器:

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
@Component
public class CustomNotifier extends AbstractStatusChangeNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger( LoggingNotifier.class);

public CustomNotifier(InstanceRepository repository) {
super(repository);
}

@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
return Mono.fromRunnable(() -> {
if (event instanceof InstanceStatusChangedEvent) {
LOGGER.info("Instance {} ({}) is {}", instance.getRegistration().getName(), event.getInstance(),
((InstanceStatusChangedEvent) event).getStatusInfo().getStatus());

String status = ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus();

switch (status) {
// 健康检查没通过
case "DOWN":
System.out.println("发送 健康检查没通过 的通知!");
break;
// 服务离线
case "OFFLINE":
System.out.println("发送 服务离线 的通知!");
break;
//服务上线
case "UP":
System.out.println("发送 服务上线 的通知!");
break;
// 服务未知异常
case "UNKNOWN":
System.out.println("发送 服务未知异常 的通知!");
break;
default:
break;
}

} else {
LOGGER.info("Instance {} ({}) {}", instance.getRegistration().getName(), event.getInstance(),
event.getType());
}
});
}
}

源码下载:https://github.com/gf-huanchupk/SpringBootLearning/tree/master/springboot-admin

SpringBoot 整合 docker

发表于 2019-03-08 | 分类于 SpringBoot

一、什么是docker ?

简介

Docker是一个开源的引擎,可以轻松的为任何应用创建一个轻量级的、可移植的、自给自足的容器。开发者在笔记本上编译测试通过的容器可以批量地在生产环境中部署,包括VMs(虚拟机)、bare metal、OpenStack 集群和其他的基础应用平台。

docker的应用场景

  • web应用的自动化打包和发布;
  • 自动化测试和持续集成、发布;
  • 在服务型环境中部署和调整数据库或其他的后台应用;
  • 从头编译或者扩展现有的OpenShift或Cloud Foundry平台来搭建自己的PaaS环境。

对于docker的使用,我后期会开专题详细讲解。

二、整合 docker

创建工程

创建一个springboot工程springboot-docker

1. 启动类

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

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class SpringbootDockerApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootDockerApplication.class, args);
}

@GetMapping("/{name}")
public String hi(@PathVariable(value = "name") String name) {
return "hi , " + name;
}


}

2. 将springboot工程容器化

我们编写一个Dockerfile来定制镜像,在src/main/resources/docker 下创建Dockerfile文件

1
2
3
4
5
6
FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD springboot-docker-0.0.1-SNAPSHOT.jar app.jar
RUN sh -c 'touch /app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]

3. pom.xml

我们通过maven 构建docker镜像。
在maven的pom目录,加上docker镜像构建的插件

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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gf</groupId>
<artifactId>springboot-docker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-docker</name>
<description>Demo project for Spring Boot</description>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<docker.image.prefix>gf</docker.image.prefix>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>



<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>1.2.0</version>
<configuration>
<imageName>${docker.image.prefix}/${project.artifactId}</imageName>
<dockerDirectory>src/main/resources/docker</dockerDirectory>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>
</plugins>
</build>


</project>

构建镜像

我们运行下面的命令构建镜像:

1
2
mvn clean
mvn package docker:bulid

构建成功后,我们通过下面的命令查看镜像:

1
docker images

启动镜像:

1
2
#c2dba352c3c1 为镜像ID
docker run -p 8080:8080 -t c2dba352c3c1

之后我们就可以访问服务了。

源码下载:https://github.com/gf-huanchupk/SpringBootLearning

SpringBoot 整合 rabbitmq

发表于 2019-03-08 | 分类于 SpringBoot

一、消息中间件的应用场景

异步处理

场景:用户注册,信息写入数据库后,需要给用户发送注册成功的邮件,再发送注册成功的邮件。

1.同步调用:注册成功后,顺序执行发送邮件方法,发送短信方法,最后响应用户

2.并行调用:注册成功后,用多线程的方式并发执行发邮件和发短信方法,最后响应用户

3.消息队列:注册成功后,将要发送的消息用很短的时间写入消息队列中,之后响应用户;发送邮件的服务和发送短息的服务就可以从消息队列中异步读去,然后发送任务。

应用解耦

场景:购物下单后,调用库存系统,更新库存。

1.耦合的方式:订单系统,写调用库存系统的逻辑。

2.解耦的方式:订单系统,将下达的消息写入消息队列,库存系统从消息队列中读取消息,更新库存。

流量削峰

秒杀场景中,我们可以设置一个定长的消息队列,秒杀开始,谁快谁先进入队列,然后快速返回用户是否秒到 ,之后在平稳的处理秒杀后的业务。

二、消息服务中间件概述

    1. 大多应用中,可通过消息服务中间件来提升系统异步通信、扩展解耦能力
    1. 消息服务中两个重要概念:
      消息代理(message broker)和目的地(destination) 当消息发送者发送消息以后,将由消息代理接管,消息代理保证消息传递到指定目
      的地。
    1. 消息队列主要有两种形式的目的地
      1. 队列(queue):点对点消息通信(point-to-point)
      1. 主题(topic):发布(publish)/订阅(subscribe)消息通信
    1. 点对点式:
      1. 消息发送者发送消息,消息代理将其放入一个队列中,消息接收者从队列中获取消息内容, 消息读取后被移出队列
      1. 消息只有唯一的发送者和接受者,但并不是说只能有一个接收者
    1. 发布订阅式:
    • 发送者(发布者)发送消息到主题,多个接收者(订阅者)监听(订阅)这个主题,那么 就会在消息到达时同时收到消息
    1. JMS(Java Message Service)JAVA消息服务:
    • 基于JVM消息代理的规范。ActiveMQ、HornetMQ是JMS实现
    1. AMQP(Advanced Message Queuing Protocol)
    • 高级消息队列协议,也是一个消息代理的规范,兼容JMS
    • RabbitMQ是AMQP的实现

    1. Spring支持
    • spring-jms提供了对JMS的支持
    • spring-rabbit提供了对AMQP的支持
    • 需要ConnectionFactory的实现来连接消息代理
    • 提供JmsTemplate、RabbitTemplate来发送消息
    • @JmsListener(JMS)、@RabbitListener(AMQP)注解在方法上监听消息代理发 布的消息
    • @EnableJms、@EnableRabbit开启支持
    1. Spring Boot自动配置
    • JmsAutoConfiguration
    • RabbitAutoConfiguration

三、RabbitMQ简介

RabbitMQ是一个由erlang开发的AMQP(Advanved Message Queue Protocol)的开源实现。

1. 核心概念

  • Message :消息,消息是不具名的,它由消息头和消息体组成。消息体是不透明的,而消息头则由一系列的可选属性组 成,这些属性包括routing-key(路由键)、priority(相对于其他消息的优先权)、delivery-mode(指出 该消息可能需要持久性存储)等。
  • Publisher :消息的生产者,也是一个向交换器发布消息的客户端应用程序。
  • Exchange :交换器,用来接收生产者发送的消息并将这些消息路由给服务器中的队列。Exchange有4种类型:direct(默认),fanout, topic, 和headers,不同类型的Exchange转发消息的策略有所区别
  • Queue :消息队列,用来保存消息直到发送给消费者。它是消息的容器,也是消息的终点。一个消息可投入一个或多个队列。消息一直在队列里面,等待消费者连接到这个队列将其取走。
  • Binding :绑定,用于消息队列和交换器之间的关联。一个绑定就是基于路由键将交换器和消息队列连接起来的路由规则,所以可以将交换器理解成一个由绑定构成的路由表。Exchange 和Queue的绑定可以是多对多的关系。
  • Connection :网络连接,比如一个TCP连接。
  • Channel :信道,多路复用连接中的一条独立的双向数据流通道。信道是建立在真实的TCP连接内的虚 拟连接,AMQP 命令都是通过信道发出去的,不管是发布消息、订阅队列还是接收消息,这 些动作都是通过信道完成。因为对于操作系统来说建立和销毁 TCP 都是非常昂贵的开销,所 以引入了信道的概念,以复用一条 TCP 连接。
  • Consumer :消息的消费者,表示一个从消息队列中取得消息的客户端应用程序。
  • Virtual Host :虚拟主机,表示一批交换器、消息队列和相关对象。虚拟主机是共享相同的身份认证和加 密环境的独立服务器域。每个 vhost 本质上就是一个 mini 版的 RabbitMQ 服务器,拥有 自己的队列、交换器、绑定和权限机制。vhost 是 AMQP 概念的基础,必须在连接时指定, RabbitMQ 默认的 vhost 是 / 。
  • Broker :表示消息队列服务器实体。

四、RabbitMQ运行机制

AMQP 中的消息路由

AMQP 中消息的路由过程和 Java 开发者熟悉的 JMS 存在一些差别,AMQP 中增加了 Exchange 和 Binding 的角色。生产者把消息发布到 Exchange 上,消息最终到达队列并被 消费者接收,而 Binding 决定交换器的消息应该发送到那个队列。

Exchange 类型

Exchange分发消息时根据类型的不同分发策略有区别,目前共四种类型:direct、fanout、topic、headers 。headers 匹配 AMQP 消息的 header 而不是路由键, headers 交换器和 direct 交换器完全一致,但性能差很多,目前几乎用不到了,所以直接看另外三种类型:

五、RabbitMQ安装

我们使用 docker 来安装 RabbitMQ。
我们在 docker hub上选择官方的带management管理界面的最新版本。

1
2
3
4
#获取rabbitmq镜像
docker pull rabbitmq:3-management
#启动 rabbitmq镜像,5672是mq通信端口,15672是mq的web管理界面端口
run -d -p 5672:5672 -p 15672:15672 --name myrabbitmq 镜像ID

访问127.0.0.1:15672 ,用账号:guest 密码:guest 登录,界面如下:

对rabbitmq的详细使用在这里,就不讲解了,我们这节的重点是整合rabbitmq。

六、整合RabbitMQ

创建项目引入rabbitmq依赖。

1. pom.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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.gf</groupId>
<artifactId>springboot-rabbitmq</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springboot-rabbitmq</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

2. MyAMQPConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.gf.config;

import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.support.converter.MessageConverter;

/**
* 自定义消息转换器,默认是jdk的序列化转换器,我们自定义为json的
*/
@Configuration
public class MyAMQPConfig {

@Bean
public MessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}

}

3. springboot 测试类

我们测试创建管理配置、发送消息、接收消息

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
package com.gf;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRabbitmqApplicationTests {

@Autowired
RabbitTemplate rabbitTemplate;

@Autowired
AmqpAdmin amqpAdmin;

@Test
public void contextLoads() {
}

@Test
public void create(){
//创建Exchange
amqpAdmin.declareExchange( new DirectExchange( "exchange.direct") );
amqpAdmin.declareExchange( new FanoutExchange( "exchange.fanout") );
amqpAdmin.declareExchange( new TopicExchange( "exchange.topic") );

//创建Queue
amqpAdmin.declareQueue( new Queue( "direct.queue" , true ) );
amqpAdmin.declareQueue( new Queue( "fanout.queue" , true ) );

//绑定Queue
amqpAdmin.declareBinding( new Binding( "direct.queue" , Binding.DestinationType.QUEUE , "exchange.direct" , "direct.queue" , null ) );
amqpAdmin.declareBinding( new Binding( "fanout.queue" , Binding.DestinationType.QUEUE , "exchange.direct" , "fanout.queue" , null ) );
amqpAdmin.declareBinding( new Binding( "direct.queue" , Binding.DestinationType.QUEUE , "exchange.fanout" , "" , null ) );
amqpAdmin.declareBinding( new Binding( "fanout.queue" , Binding.DestinationType.QUEUE , "exchange.fanout" , "" , null ) );
amqpAdmin.declareBinding( new Binding( "direct.queue" , Binding.DestinationType.QUEUE , "exchange.topic" , "direct.#" , null ) );
amqpAdmin.declareBinding( new Binding( "fanout.queue" , Binding.DestinationType.QUEUE , "exchange.topic" , "direct.*" , null ) );


}

@Test
public void send2Direct() {
Map<String , Object> map = new HashMap<>();
map.put( "msg" , "这是一条点对点消息" );
map.put( "data" , Arrays.asList("helloworld" , 123 , true) );

rabbitTemplate.convertAndSend( "exchange.direct" , "direct.queue" , map );

}

@Test
public void send2Topic() {
Map<String , Object> map = new HashMap<>();
map.put( "msg" , "这是一条广播消息" );
map.put( "data" , Arrays.asList("topic消息" , 123 , true) );

rabbitTemplate.convertAndSend( "exchange.fanout" , "", map );

}

@Test
public void receive() {
Object o = rabbitTemplate.receiveAndConvert( "direct.queue" );
o.getClass();
System.out.println(o.getClass());
System.out.println(o);
}

}

监听消息

4. 启动类

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

import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* 自动配置
* 1. RabbitAutoConfiguration
* 2. 自动配置了连接工厂ConnectionFactory
* 3. RabbitProperties 封装了RabbitMQ的配置
* 4. RabbitTemplate : 给RabbitMQ发送和接受消息
* 5. AmqpAdmin : RabbitMQ系统管理功能组件
* 6. @EnableRabbit + @RabbitListener
*/
@EnableRabbit
@SpringBootApplication
public class SpringbootRabbitmqApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootRabbitmqApplication.class, args);
}
}

5. MQService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.gf.service;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class MQService {

@RabbitListener(queues = "fanout.queue")
public void receive(Message message) {
System.out.println("收到消息 : " + new String(message.getBody()));

}

}

源码下载:https://github.com/gf-huanchupk/SpringBootLearning

SpringBoot 整合 elasticsearch

发表于 2019-03-08 | 分类于 SpringBoot

一、简介

我们的应用经常需要添加检索功能,开源的 ElasticSearch 是目前全文搜索引擎的 首选。他可以快速的存储、搜索和分析海量数据。Spring Boot通过整合Spring Data ElasticSearch为我们提供了非常便捷的检索功能支持;
Elasticsearch是一个分布式搜索服务,提供Restful API,底层基于Lucene,采用 多shard(分片)的方式保证数据安全,并且提供自动resharding的功能,github 等大型的站点也是采用了ElasticSearch作为其搜索服务,

二、安装elasticsearch

我们采用 docker镜像安装的方式。

1
2
3
4
5
#下载镜像
docker pull elasticsearch
#启动镜像,elasticsearch 启动是会默认分配2G的内存 ,我们启动是设置小一点,防止我们内存不够启动失败
#9200是elasticsearch 默认的web通信接口,9300是分布式情况下,elasticsearch个节点通信的端口
docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 --name es01 5c1e1ecfe33a

访问 127.0.0.1:9200 如下图,说明安装成功

三、elasticsearch的一些概念

  • 以 员工文档 的形式存储为例:一个文档代表一个员工数据。存储数据到 ElasticSearch 的行为叫做索引 ,但在索引一个文档之前,需要确定将文档存 储在哪里。
  • 一个 ElasticSearch 集群可以 包含多个索引 ,相应的每个索引可以包含多个类型。这些不同的类型存储着多个文档 ,每个文档又有 多个 属性 。
  • 类似关系:
    • 索引-数据库
    • 类型-表
    • 文档-表中的记录 – 属性-列

elasticsearch使用可以参早官方文档,在这里不在讲解。

四、整合 elasticsearch

创建项目 springboot-elasticsearch,引入web支持
SpringBoot 提供了两种方式操作elasticsearch,Jest 和 SpringData。

Jest 操作 elasticsearch

Jest是ElasticSearch的Java HTTP Rest客户端。

ElasticSearch已经有一个Java API,ElasticSearch也在内部使用它,但是Jest填补了空白,它是ElasticSearch Http Rest接口缺少的客户端。

1. pom.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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.gf</groupId>
<artifactId>springboot-elasticsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springboot-elasticsearch</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>5.3.3</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


</project>

2. application.properties

1
spring.elasticsearch.jest.uris=http://127.0.0.1:9200

3. Article

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
package com.gf.entity;


import io.searchbox.annotations.JestId;

public class Article {

@JestId
private Integer id;
private String author;
private String title;
private String content;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

@Override
public String toString() {
final StringBuilder sb = new StringBuilder( "{\"Article\":{" );
sb.append( "\"id\":" )
.append( id );
sb.append( ",\"author\":\"" )
.append( author ).append( '\"' );
sb.append( ",\"title\":\"" )
.append( title ).append( '\"' );
sb.append( ",\"content\":\"" )
.append( content ).append( '\"' );
sb.append( "}}" );
return sb.toString();
}


}

4. springboot测试类

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 com.gf;

import com.gf.entity.Article;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootElasticsearchApplicationTests {

@Autowired
JestClient jestClient;

@Test
public void createIndex() {
//1. 给ES中索引(保存)一个文档
Article article = new Article();
article.setId( 1 );
article.setTitle( "好消息" );
article.setAuthor( "张三" );
article.setContent( "Hello World" );

//2. 构建一个索引
Index index = new Index.Builder( article ).index( "gf" ).type( "news" ).build();
try {
//3. 执行
jestClient.execute( index );
} catch (IOException e) {
e.printStackTrace();
}
}

@Test
public void search() {
//查询表达式
String query = "{\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"content\" : \"hello\"\n" +
" }\n" +
" }\n" +
"}";

//构建搜索功能
Search search = new Search.Builder( query ).addIndex( "gf" ).addType( "news" ).build();

try {
//执行
SearchResult result = jestClient.execute( search );
System.out.println(result.getJsonString());
} catch (IOException e) {
e.printStackTrace();
}

}

}

Jest的更多api ,可以参照github的文档:https://github.com/searchbox-io/Jest

SpringData 操作 elasticsearch

1. application.properties

1
2
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300

2. Book

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 com.gf.entity;

@Document( indexName = "gf" , type = "book")
public class Book {
private Integer id;
private String bookName;
private String author;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getBookName() {
return bookName;
}

public void setBookName(String bookName) {
this.bookName = bookName;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

@Override
public String toString() {
final StringBuilder sb = new StringBuilder( "{\"Book\":{" );
sb.append( "\"id\":" )
.append( id );
sb.append( ",\"bookName\":\"" )
.append( bookName ).append( '\"' );
sb.append( ",\"author\":\"" )
.append( author ).append( '\"' );
sb.append( "}}" );
return sb.toString();
}

}

3. BookRepository

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.gf.repository;


import com.gf.entity.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

public interface BookRepository extends ElasticsearchRepository<Book, Integer>{

List<Book> findByBookNameLike(String bookName);

}

4. springboot 测试类

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
package com.gf;

import com.gf.entity.Article;
import com.gf.entity.Book;
import com.gf.repository.BookRepository;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootElasticsearchApplicationTests {

@Autowired
BookRepository bookRepository;

@Test
public void createIndex2(){
Book book = new Book();
book.setId(1);
book.setBookName("西游记");
book.setAuthor( "吴承恩" );
bookRepository.index( book );
}

@Test
public void useFind() {
List<Book> list = bookRepository.findByBookNameLike( "游" );
for (Book book : list) {
System.out.println(book);
}

}

}

我们启动测试 ,发现报错 。

这个报错的原因是springData的版本与我elasticsearch的版本有冲突,下午是springData官方文档给出的适配表。

我们使用的springdata elasticsearch的 版本是3.1.3 ,对应的版本应该是6.2.2版本,而我们是的 elasticsearch 是 5.6.9,所以目前我们需要更换elasticsearch的版本为6.X

1
2
docker pull elasticsearch:6.5.1
docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 --name es02 镜像ID

访问127.0.0.1:9200

集群名为docker-cluster,所以我们要修改application.properties的配置了

1
2
spring.data.elasticsearch.cluster-name=docker-cluster
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300

我们再次进行测试,测试可以通过了 。我们访问http://127.0.0.1:9200/gf/book/1,可以得到我们存入的索引信息。

源码下载:https://github.com/gf-huanchupk/SpringBootLearning

SpringBoot 整合 elk

发表于 2019-03-08 | 分类于 SpringBoot

一、elk 简介

  • Elasticsearch是个开源分布式搜索引擎,它的特点有:分布式,零配置,自动发现,索引自动分片,索引副本机制,restful风格接口,多数据源,自动搜索负载等。

  • Logstash是一个完全开源的工具,他可以对你的日志进行收集、过滤,并将其存储供以后使用(如,搜索)。

  • Kibana 也是一个开源和免费的工具,它Kibana可以为 Logstash 和 ElasticSearch 提供的日志分析友好的 Web 界面,可以帮助您汇总、分析和搜索重要数据日志。

二、elk的安装

我们采用的 docker 镜像安装。

1
2
#下载镜像
docker pull sebp/elk
1
2
#启动镜像 , 指定es的内存
docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -p 5601:5601 -p 5044:5044 -p 9200:9200 -p 9300:9300 -it --name elk 2fbf0a30426d

我们访问http://127.0.0.1:5601

三、创建工程

创建工程springboot-elk ,并使用logback 记录日志。

1. pom.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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.gf</groupId>
<artifactId>springboot-elk</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springboot-elk</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!-- logback -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>

<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>5.2</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>

</project>

2. 启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RestController
@SpringBootApplication
public class SpringbootElkApplication {

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

public static void main(String[] args) {
SpringApplication.run(SpringbootElkApplication.class, args);
}

@GetMapping("/{name}")
public String hi(@PathVariable(value = "name") String name) {
logger.info( "name = {}" , name );
return "hi , " + name;
}
}

3. logback-spring.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
<?xml version="1.0" encoding="UTF-8"?>
<!--该日志将日志级别不同的log信息保存到不同的文件中 -->
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />

<springProperty scope="context" name="springAppName"
source="spring.application.name" />

<!-- 日志在工程中的输出位置 -->
<property name="LOG_FILE" value="${BUILD_FOLDER:-build}/${springAppName}" />

<!-- 控制台的日志输出样式 -->
<property name="CONSOLE_LOG_PATTERN"
value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}" />

<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<!-- 日志输出编码 -->
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>

<!-- 为logstash输出的JSON格式的Appender -->
<appender name="logstash"
class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>127.0.0.1:5044</destination>
<!-- 日志输出编码 -->
<encoder
class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<timestamp>
<timeZone>UTC</timeZone>
</timestamp>
<pattern>
<pattern>
{
"severity": "%level",
"service": "${springAppName:-}",
"trace": "%X{X-B3-TraceId:-}",
"span": "%X{X-B3-SpanId:-}",
"exportable": "%X{X-Span-Export:-}",
"pid": "${PID:-}",
"thread": "%thread",
"class": "%logger{40}",
"rest": "%message"
}
</pattern>
</pattern>
</providers>
</encoder>
</appender>

<!-- 日志输出级别 -->
<root level="INFO">
<appender-ref ref="console" />
<appender-ref ref="logstash" />
</root>

</configuration>

启动工程,日志会存入elasticsearch中,通过Kibana 的web界面,配置后,我们就可看到,下面我简单的修改下配置。

三、配置 pattern

配置 pattern 输入*,匹配所有数据。

选择时间@timestamp,这样数据展示会以时间排序

好了 ,点击discover,就可以看到我们springboot-elk项目的日志信息了。

源码下载: https://github.com/gf-huanchupk/SpringBootLearning

SpringBoot 整合 apollo

发表于 2019-03-08 | 分类于 SpringBoot

简介

Apollo(阿波罗)是携程框架部门研发的分布式配置中心,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性,适用于微服务配置管理场景。

Apollo和Spring Cloud Config对比

通过对比,可以看出,生成环境中 Apollo 相比 Spring Cloud Config 更具有优势一些。

安装 Apollo 配置中心

搭建教程

参照 https://github.com/ctripcorp/apollo/wiki/Quick-Start 搭建 Apollo 配置中心,文档写的很清楚,这里就赘述了。

查看样例配置

搭建完成并启动后,访问 http://localhost:8070 ,界面如下。

输入用户名 apollo,密码 admin 后登录后,点击SampleApp进入配置界面。

与 Spring Boot 整合使用

创建一个springboot项目,主要代码如下。

pom.xml

添加 Apollo 客户端的依赖,为了编码方便引入commons-lang3。

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.3.0</version>
</dependency>
<!-- 为了编码方便,并非apollo 必须的依赖 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>

application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server:
port: 8761

app:
id: springboot-apollo
apollo:
meta: http://127.0.0.1:8080
bootstrap:
enabled: true
eagerLoad:
enabled: true

logging:
level:
com:
gf:
controller: debug

配置说明:

  • app.id:AppId是应用的身份信息,是配置中心获取配置的一个重要信息。
  • apollo.bootstrap.enabled:在应用启动阶段,向Spring容器注入被托管的application.properties文件的配置信息。
  • apollo.bootstrap.eagerLoad.enabled:将Apollo配置加载提到初始化日志系统之前。
  • logging.level.com.gf.controller:调整 controller 包的 log 级别,为了后面演示在配置中心动态配置日志级别。

HelloController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RestController
public class HelloController {

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

@Value( "${server.port}" )
String port;

@GetMapping("hi")
public String hi(String name) {

logger.debug( "debug log..." );
logger.info( "info log..." );
logger.warn( "warn log..." );

return "hi " + name + " ,i am from port:" + port;
}

}

启动类

1
2
3
4
5
6
7
8
9
10
@SpringBootApplication
@EnableApolloConfig
public class SpringbootApolloApplication {

public static void main(String[] args) {
SpringApplication.run( SpringbootApolloApplication.class, args );
}


}

启动项目。现在需要去配置中心做些关于这个springboot客户端的一些配置。

配置中心的配置

创建项目

第一步:访问http://localhost:8070 登录后,选择创建项目。

第二步:填写配置信息。

配置说明:

  • 部门:选择应用所在的部门。(想自定义部门,参照官方文档,这里就选择样例)
  • 应用AppId:用来标识应用身份的唯一id,格式为string,需要和客户端。application.properties中配置的app.id对应。
  • 应用名称:应用名,仅用于界面展示。
  • 应用负责人:选择的人默认会成为该项目的管理员,具备项目权限管理、集群创建、Namespace创建等权限。

提交配置后会出现如下项目配置的管理页面。

添加配置项

第一步:点击 “新增配置”,配置需要管理的 application.properties 中的属性。

点击提交,之后按照同样的方法,新增需要动态管理的 application.properties 中的属性。

提交后,跳转到配置的管理界面:

发布配置

配置只有在发布后才会真的被应用使用到,所以在编辑完配置后,需要发布配置。点击“发布按钮”。

填写发布相关信息,点击发布 。

测试

在配置中心,修改 server.port 的值为 8762 并发布。

Postman 访问之前写个测试接口 http://127.0.0.1:8761/hi?name=zhangsan ,返回如下。

说明 客户端 获取到了 配置中心修改后的 server.port 的值 。

注意:

  • 服务的端口依然还是 8761,这是因为 apollo 修改配置,不会像Spring Cloud Config 那样去重启应用。
  • 重启应用后,客户端会加载使用 配置中心中配置的属性的值,例如我们重启我们的应用,服务端口会变成8762。

监听配置的变化

需求

日志模块是每个项目中必须的,用来记录程序运行中的相关信息。一般在开发环境下使用DEBUG级别的日志输出,为了方便查看问题,而在线上一般都使用INFO或者ERROR级别的日志,主要记录业务操作或者错误的日志。那么问题来了,当线上环境出现问题希望输出DEBUG日志信息辅助排查的时候怎么办呢?修改配置文件,重新打包然后上传重启线上环境,以前确实是这么做的。

虽然上面我们已经把日志的配置部署到Apollo配置中心,但在配置中心修改日志等级,依然需要重启应用才生效,下面我们就通过监听配置的变化,来达到热更新的效果。

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
@Configuration
public class LoggerConfig {

private static final Logger logger = LoggerFactory.getLogger(LoggerConfig.class);
private static final String LOGGER_TAG = "logging.level.";

@Autowired
private LoggingSystem loggingSystem;

@ApolloConfig
private Config config;

@ApolloConfigChangeListener
private void configChangeListter(ConfigChangeEvent changeEvent) {
refreshLoggingLevels();
}

@PostConstruct
private void refreshLoggingLevels() {
Set<String> keyNames = config.getPropertyNames();
for (String key : keyNames) {
if (StringUtils.containsIgnoreCase(key, LOGGER_TAG)) {
String strLevel = config.getProperty(key, "info");
LogLevel level = LogLevel.valueOf(strLevel.toUpperCase());
loggingSystem.setLogLevel(key.replace(LOGGER_TAG, ""), level);
logger.info("{}:{}", key, strLevel);
}
}
}


}

关键点讲解:

  • @ApolloConfig注解:将Apollo服务端的中的配置注入这个类中。
  • @ApolloConfigChangeListener注解:监听配置中心配置的更新事件,若该事件发生,则调用refreshLoggingLevels方法,处理该事件。
  • ConfigChangeEvent参数:可以获取被修改配置项的key集合,以及被修改配置项的新值、旧值和修改类型等信息。

application.yml 中配置的日志级别是 debug ,访问http://127.0.0.1:8761/hi?name=zhangsan ,控制台打印如下。

1
2
3
2019-03-05 18:29:22.673 DEBUG 4264 --- [nio-8762-exec-1] com.gf.controller.HelloController        : debug log...
2019-03-05 18:29:22.673 INFO 4264 --- [nio-8762-exec-1] com.gf.controller.HelloController : info log...
2019-03-05 18:29:22.673 WARN 4264 --- [nio-8762-exec-1] com.gf.controller.HelloController : warn log...

现在在配置中心修改日志级别为 warn。

再次访问http://127.0.0.1:8761/hi?name=zhangsan ,控制台打印如下。

1
2019-03-05 19:07:19.469  WARN 4264 --- [nio-8762-exec-3] com.gf.controller.HelloController        : warn log...

说明日志级别的配置,已经支持热更新了。关于apollo 的更多应用 ,可以参照github的文档。

源码下载 : https://github.com/gf-huanchupk/SpringBootLearning/tree/master/springboot-apollo

12
程序员果果

程序员果果

17 日志
3 分类
22 标签
GitHub E-Mail
© 2019 程序员果果
由 Hexo 强力驱动 v3.8.0
|
主题 – NexT.Gemini v7.0.1