SpringBootAdmin搭建教程八:微服务开发Consul注册中心整合SpringBootAdmin

上一篇中我们学习了使用微服务中的Eureka 注册发现来整合SpringBootAdmin 进行监控等操作,这一篇我们来学习Consul注册中心整合SpringBootAdmin。

Consul介绍

Consul是一种网络工具,可提供功能全面的服务网格和服务发现。
Consul 官方文档 ,请看视频教程来学习 Consul 官方文档
这里我就用本地来演示,工作中肯定是部署到云上面来使用的。
官方下载地址: Consul 下载地址
选择好对应的安装版本,本例子用 Windows来做,下载解压出来后是 consul.exe
解压后里面就一个文件consul, 将这个文件放到你的PATH,注意一定要配置好环境变量才能使用哦。
验证consul

consul  version

启动consul

consul agent --server=true --ui=true --data-dir=/tmp/consul --node=server1 --dev

上面的 --server表示以server方式,--ui 会开启一个web ui管理界面, --dev 表示开发者模式,不需要ACL验证。不然那个web ui的打不开会报没有权限
启动成功后,访问 http://localhost:8500/ 出现以下界面说明安装成功了。

在这里插入图片描述
Services 是注册的服务,如果没有注册过,那就是没有。

Consul整合SpringBootAdmin

创建一个spring boot 项目添加对应的Consul 依赖,来做整合实例。

pom.xml

<?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 https://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.3.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>adminconsul</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>adminconsul</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
		<!-- spring-cloud 版本 如果 出现 与 springboot 版本不一致的情况 请查看 https://spring.io/projects/spring-cloud#overview-->
		<spring-cloud.version>Hoxton.SR8</spring-cloud.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<!-- spring-boot-admin 服务端-->
		<dependency>
			<groupId>de.codecentric</groupId>
			<artifactId>spring-boot-admin-starter-server</artifactId>
			<exclusions>
				<exclusion>
					<groupId>io.projectreactor.netty</groupId>
					<artifactId>reactor-netty</artifactId>
				</exclusion>
			</exclusions>
			<version>2.3.0</version>
		</dependency>

		<dependency>
			<groupId>io.projectreactor.netty</groupId>
			<artifactId>reactor-netty</artifactId>
			<version>0.9.10.RELEASE</version>
		</dependency>

		<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>
		<!-- consul -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-consul-discovery</artifactId>
		</dependency>
		<!-- 安全授权 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

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

	<!-- spring-cloud -->
	<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>
		</dependencies>
	</dependencyManagement>

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

yml配置

spring:
  application:
    name: consul-example
  cloud:
    config:
      enabled: false
    consul:
      host: localhost
      port: 8500
      discovery:
        tags: management.context-path=/foo, health.path=/ping, user.name=admin, user.password=admin
  profiles:
    active:
      - secure
  boot:
    admin:
      discovery:
        ignored-services: consul


management:
  endpoints:
    web:
      exposure:
        include: "*"
      path-mapping:
        health: /ping
      base-path: /foo
  endpoint:
    health:
      show-details: ALWAYS

---
spring:
  profiles: insecure

---
spring:
  profiles: secure
  security:
    user:
      name: "admin"
      password: "admin"

代码中配置 安全授权:

启动类上面加上注解:
@EnableDiscoveryClient
@EnableAdminServer
配置也是在启动类中去做。

@SpringBootApplication
@EnableDiscoveryClient
@EnableAdminServer
public class AdminconsulApplication {

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

    @Profile("insecure")
    @Configuration(proxyBeanMethods = false)
    public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {

        private final String adminContextPath;

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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests((authorizeRequests) -> authorizeRequests.anyRequest().permitAll())
                    .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                            .ignoringRequestMatchers(
                                    new AntPathRequestMatcher(this.adminContextPath + "/instances",
                                            HttpMethod.POST.toString()),
                                    new AntPathRequestMatcher(this.adminContextPath + "/instances/*",
                                            HttpMethod.DELETE.toString()),
                                    new AntPathRequestMatcher(this.adminContextPath + "/actuator/**")));
        }

    }

    @Profile("secure")
    @Configuration(proxyBeanMethods = false)
    public static class SecuritySecureConfig extends WebSecurityConfigurerAdapter {

        private final String adminContextPath;

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

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

            http.authorizeRequests((authorizeRequests) -> authorizeRequests
                    .antMatchers(this.adminContextPath + "/assets/**").permitAll()
                    .antMatchers(this.adminContextPath + "/login").permitAll().anyRequest().authenticated())
                    .formLogin((formLogin) -> formLogin.loginPage(this.adminContextPath + "/login")
                            .successHandler(successHandler))
                    .logout((logout) -> logout.logoutUrl(this.adminContextPath + "/logout"))
                    .httpBasic(Customizer.withDefaults())
                    .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                            .ignoringRequestMatchers(
                                    new AntPathRequestMatcher(this.adminContextPath + "/instances",
                                            HttpMethod.POST.toString()),
                                    new AntPathRequestMatcher(this.adminContextPath + "/instances/*",
                                            HttpMethod.DELETE.toString()),
                                    new AntPathRequestMatcher(this.adminContextPath + "/actuator/**")));
        }

    }

}

以上做完之后,就启动当前项目,在启动之前要先保证consul 在运行当前,不然注册不进去实例。
启动成功后,查看consul 界面有没有注册进行的实例,如果有,那么就登录adminservice
在这里插入图片描述
输入配置好的用户名和密码,
在这里插入图片描述已经能读取到注册中心的实例了。

在这里插入图片描述
说明整合成功了,启动的配置也是一样的,比如日志配置,邮箱配置,记住登录等,在前面已经有了,自己可以去试着去玩玩。
完整实例代码,GitHub: SpringBootAmdinDemo
有问题下方讨论,一起学习。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值