Getting SpringCloud take you through the auto-update configuration SpringCloud Bus

Foreword

In the "take you on SpringCloud unified configuration | SpringCloud Config" to complete the unified configuration basis for setting up the environment by SpringCloud Config, but did not realize configuration modification operation is automatically updated (GitHub or Gitee After modifying the configuration, you need to restart the configuration service to update configuration) .

This article is a "take you on SpringCloud unified configuration | SpringCloud Config" sequel, complete configuration changes introduced by the automatic updates of the operating SpringCloud Bus.

Before reading this article you need to venue "take you on SpringCloud unified configuration | SpringCloud Config" because this article is to explain in its basis.

In addition you need to be familiar with the basic use of SpringBoot project is also important to note that as far as possible and consistent with my local environment during operation, because the environment inconsistencies may cause some problems. My local environment as follows:

  • SpringBoot Version: 2.1.0.RELEASE
  • SpringCloud Version: Greenwich.RELEASE
  • Apache Maven Version: 3.6.0
  • Java Version: 1.8.0_144
  • IDEA:Spring Tools Suite (STS)

Then we start to build the operating environment SpringCloud Bus Introduction!

SpringCloud Bus environment to build

Step 1: Install and enable RabbitMQ, here is not described in detail. Before you can view the summary: Windows environment to install RabbitMQ

If you do not end RabbitMQ and Config Server on a single machine, or port, username, password instead of using the default configuration, then you need to perform the following configurations in Config Server end application.properties

spring.rabbitmq.host = rabbitmq service IP address
spring.rabbitmq.port = rabbitmq port services
spring.rabbitmq.username = rabbitmq service user name
spring.rabbitmq.password = rabbitmq service password

Step Two: In the Config Server client end to end and the introduction of spring-cloud-starter-bus-amqp dependence. Specific code as follows:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

The third step: to add follows application.properties Config Server end, the object is exposed to refresh configuration interface specific configuration is as follows:

management.endpoints.web.exposure.include=  *

Step Four: Config Client end of the introduction openfeign starter dependent, specific code as follows:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

Step Five: Verify Config Server Config Client-side end and is registered in the queue and RabbitMQ is registered to the Eureka Server side. As shown below:

We need to start Eureka Server server, and then in turn starts Config Server Config Client-side and end.

Here Insert Picture Description
Here Insert Picture Description
Step Six: Access configured on the Config Client-side Controller statement refresh configuration scope @RefreshScope. Specific code as follows:

@RestController
@RefreshScope
public class EvnController {
    @Value("${env}")
    private String env;
    
    @RequestMapping("/env")
    public String evn() {
        return this.env;
    }
}

Do not add @RefreshScope notes, will not take effect after the configuration update.
If you need to add a custom prefix configuration can @RefreshScope in @ConfigurationProperties,

Most seven-step WebHooks disposed on Gitee, specific mode of operation as shown below:

Enter Gitee Click Administration, then click WebHooks.
Here Insert Picture Description
Here Insert Picture Description
Click the Add button to add a new WebHooks settings.
Here Insert Picture Description
Local mapping input external network access domain name + / actuator / bus-refresh, may be used to test their NATAPP be arranged to penetrate through the network. See the specific configuration https://natapp.cn/.
Here Insert Picture Description

test

Manually update links to access test

Modify the code cloud disposed remote repository, then use the access PostMan: http: // localhost: 8080 / actuator / bus-refresh, as shown below:

Directly demonstrated here is the operation code in the cloud, git push perform equivalent operations.

Here Insert Picture Description
Here Insert Picture Description
Then view product service (Config Client-side) configuration is effective. As shown in FIG automatically updated successfully!
Here Insert Picture Description
WebHooks test

Enter WebHooks Settings, and then click Test. Shown in FIG error will be reported as follows:
Here Insert Picture Description

solution:

Reference to CSDN author tinysakurac solutions.
Article: "solved using spring cloud config bus 400 using webhook auto-refresh problems" (https://blog.csdn.net/m0_37556444/article/details/82812816)

Causes problems: Default GitHub while performing the POST request will add such a string Body load (payload), and / actuator / bus-refresh interface to accept the information processing not performed, so the error.

Idea to solve the problem: via the interceptor intercepting bus-refresh request, then the contents of the Request Body in HttpServletRequestMapper packaging blank. Specific code as follows:

Filter intercepting bus-refresh request class.

public class BusRefreshFilter implements Filter{

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        String url = new String(httpServletRequest.getRequestURI());
        //只过滤/actuator/bus-refresh请求
        if (!url.endsWith("/bus-refresh")) {
            chain.doFilter(request, response);
            return;
        }
        //使用HttpServletRequest包装原始请求达到修改post请求中body内容的目的
        CustometRequestWrapper requestWrapper = new CustometRequestWrapper(httpServletRequest);
        chain.doFilter(requestWrapper, response);
    }
}

Custom class HttpServletRequestWrapper

public class CustometRequestWrapper extends HttpServletRequestWrapper{

    public CustometRequestWrapper(HttpServletRequest request) {
        super(request);
    }
    @Override
    public ServletInputStream getInputStream() throws IOException {
        byte[] bytes = new byte[0];
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);

        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return byteArrayInputStream.read() == -1 ? true:false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }

        
        };
    }
}

The intercepting bus-refresh request Filter added to the configuration Spring context classes.

@Configuration
public class FilterConfig {
     @Bean
        public FilterRegistrationBean<BusRefreshFilter> filterRegistration() {
            FilterRegistrationBean<BusRefreshFilter> registration = new FilterRegistrationBean<BusRefreshFilter>();
            registration.setFilter(new BusRefreshFilter());
            List<String> urlList = new ArrayList<String>();
            urlList.add("/*");
            registration.setUrlPatterns(urlList);
            registration.setName("BusRefreshFilter");
            registration.setOrder(1);
            return registration;
        }
}

Here Insert Picture Description

Then modify the configuration information on the Gitee after automatically updated, not here during the demonstration operation.

Another way is to replace the Config Server Config Server by visiting the domain name end end domain / monitor // actuator / bus-refresh. This way individuals attempt did not succeed! Official website specific configuration described below:

Many source code repository providers (such as Github, Gitlab, Gitea, Gitee, Gogs, or Bitbucket) notify you of changes in a repository through a webhook. You can configure the webhook through the provider’s user interface as a URL and a set of events in which you are interested. For instance, Github uses a POST to the webhook with a JSON body containing a list of commits and a header (X-Github-Event) set to push. If you add a dependency on the spring-cloud-config-monitor library and activate the Spring Cloud Bus in your Config Server, then a /monitor endpoint is enabled.

Add spring-cloud-config-monitor-dependent in Config Server

<dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-config-monitor</artifactId>
</dependency>

Was then added as follows Config Client:
Reference: https://github.com/spring-cloud/spring-cloud-bus/issues/124

spring.cloud.bus.id=${vcap.application.name:${spring.application.name:application}}:${vcap.application.instance_index:${spring.profiles.active:${local.server.port:${server.port:0}}}}:${vcap.application.instance_id:${random.value}}

summary

When the remote repository configuration file changes automatically configure access interface bus-refresh via GitHub or Gitee of WebHooks to notify Config Server side.

Config Server upon receiving the request clone down configuration, and then through the message queue (default RabbitMQ) transmitting the modified configuration to the Config Client terminal. Config Client-side after receiving the message to re-obtain the latest configuration information from the Config Server end.

WebHooks the bus-refresh request interface configured and arranged to send message queue are SpringCloud Bus Config Client end of help us.

The sample code

If you did not succeed to build the manner described above, you can refer to my GitHub project in spring-cloud-get-started module called a warehouse:

Cloud-config--the Spring-Service Eureka
the Spring-Cloud-config-Server
the Spring-Cloud-config-Product-Service
compare to see if misconfigured.

spring-cloud-get-started the project Address: https://github.com/zhuoqianmingyue/spring-cloud-get-started

references

https://blog.csdn.net/m0_37556444/article/details/82812816 By tinysakurac

https://cloud.spring.io/spring-cloud-config/reference/html/

Guess you like

Origin www.cnblogs.com/jerry126/p/11621334.html