跳至主要内容

Spring Boot Port Rebind

Spring Boot Port Rebind

Sometimes, our application need to be opened in one instance, we can bind to a port to make sure it. Sometimes, out application is dedicated to started in multiple instances and each one should have a different port for listening connection, we may better to let our application automatically choose in some ranges which can save much config pain.

Recently, we are trying to add health check endpoint in Syncer (a Spring Boot based data sync application), and we need to add the auto rebind functionality with Spring Boot.

Implementation

One of Spring Boot's feature is the embedded server to ease the pain to deploy, but it also encapsulate too much, making it very hard to customize by ourself, because we don’t know how it works.

We searched like Spring Boot rebind if failed, Spring Boot change server port, but only found how to customize embedded container. So, we have to do by ourselves. In order to understand how it works, we start from exception:

Exception

We start two instances of our application, and one of instances failed with LifecycleException:

2018-09-16 09:44:24,762 ERROR [] [syncer@dev@58.213.85.36] --- [main] o.apache.catalina.core.StandardService   : Failed to start connector [Connector[HTTP/1.1-9999]]
org.apache.catalina.LifecycleException: Failed to start component [Connector[HTTP/1.1-9999]]
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
	at org.apache.catalina.core.StandardService.addConnector(StandardService.java:225)
	at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.addPreviouslyRemovedConnectors(TomcatWebServer.java:255)
	at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.start(TomcatWebServer.java:197)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.startWebServer(ServletWebServerApplicationContext.java:300)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:162)
	
	// some stack trace removed ...
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
	at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:137)
	at com.github.zzt93.syncer.SyncerApplication.main(SyncerApplication.java:54)
Caused by: org.apache.catalina.LifecycleException: Protocol handler start failed
	at org.apache.catalina.connector.Connector.startInternal(Connector.java:1021)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
	... 12 common frames omitted
Caused by: java.net.BindException: Address already in use
	at sun.nio.ch.Net.bind0(Native Method)
	at sun.nio.ch.Net.bind(Net.java:433)
	at sun.nio.ch.Net.bind(Net.java:425)
	at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
	at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
	at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:210)
	at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:1150)
	at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:591)
	at org.apache.catalina.connector.Connector.startInternal(Connector.java:1018)
	... 13 common frames omitted

The first thought is to catch the LifecycleException in our code and retry with another port, but as we can see from the stack trace, Spring Boot has already done much things (finishRefresh), catch LifecycleException in main is not a good choice.

Internal

So, a better idea is to catch BindException. In order to do this , we have a serial of candidate classes to override from the stack trace:

  • Connector
  • AbstractProtocol
  • AbstractEndpoint
  • NioEndpoint

We first try to override Endpoint which seems affecting other part less, but fail to find a suitable way to inject our Endpoint. Then we try to replace default Connect with our customized, finally find we can only customize Protocol.

Code

We first customize the Bean TomcatServletWebServerFactory to affect the web server:

TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.setProtocol("com.github.zzt93.syncer.health.export.ReconnectProtocol");  
factory.setTomcatConnectorCustomizers(Lists.newArrayList((TomcatConnectorCustomizer) connector -> {  
  connector.setProperty("retry", RETRY);  
}));

And our protocol extends the default Http11NioProtocol with start method to catch bind exception and retry.

  
public class ReconnectProtocol extends Http11NioProtocol {   
  private int retry;  
  
  public void setRetry(int retry) {  
    this.retry = retry;  
  }  
  
  @Override  
  public void start() throws Exception {  
    for (int i = 0; i < retry; i++) {  
      try {  
        super.start();  
      } catch (BindException e) {  
        logger.warn("Fail to bind to {}, retry {}", getPort(), getPort()+1);  
        setPort(getPort() + 1);  
      }  
    }  
  }  
}

Ref

Written with StackEdit.

评论

此博客中的热门博文

Spring Boot: Customize Environment

Spring Boot: Customize Environment Environment variable is a very commonly used feature in daily programming: used in init script used in startup configuration used by logging etc In Spring Boot, all environment variables are a part of properties in Spring context and managed by Environment abstraction. Because Spring Boot can handle the parse of configuration files, when we want to implement a project which uses yml file as a separate config file, we choose the Spring Boot. The following is the problems we met when we implementing the parse of yml file and it is recorded for future reader. Bind to Class Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties. As the document says, there exists three ways to access properties in *.properties or *.yml : @Value : access single value Environment : can access multi...

Elasticsearch: Join and SubQuery

Elasticsearch: Join and SubQuery Tony was bothered by the recent change of search engine requirement: they want the functionality of SQL-like join in Elasticsearch! “They are crazy! How can they think like that. Didn’t they understand that Elasticsearch is kind-of NoSQL 1 in which every index should be independent and self-contained? In this way, every index can work independently and scale as they like without considering other indexes, so the performance can boost. Following this design principle, Elasticsearch has little related supports.” Tony thought, after listening their requirements. Leader notice tony’s unwillingness and said, “Maybe it is hard to do, but the requirement is reasonable. We need to search person by his friends, didn’t we? What’s more, the harder to implement, the more you can learn from it, right?” Tony thought leader’s word does make sense so he set out to do the related implementations Application-Side Join “The first implementation ...

Learn Spring Expression Language

When reading the source code of some Spring based projects, we can see some code like following: @Value( "${env}" ) private int value ; and like following: @Autowired public void configure (MovieFinder movieFinder, @ Value ("#{ systemProperties[ 'user.region' ] } ") String defaultLocale) { this.movieFinder = movieFinder; this.defaultLocale = defaultLocale; } In this way, we can inject values from different sources very conveniently, and this is the features of Spring EL. What is Spring EL? How to use this handy feature to assist our developments? Today, we are going to learn some basics of Spring EL. Features The full name of Spring EL is Spring Expression Language, which exists in form of Java string and evaluated by Spring. It supports many syntax, from simple property access to complex safe navigation – method invocation when object is not null. And the following is the feature list from Spring EL document : ...