How can I configure Netty in Spring MVC. When and where should I start the Netty tcp server? Should I init netty once the Spring starts? Could someone show me an example such as the Spring configuration xml file or something eles? Thanks!
As explained in the Spring Boot reference documentation, Spring Boot will auto-configure a Spring MVC application if both MVC and WebFlux are available.
spring-boot-starter-reactor-netty is required to use the WebClient class, so you may need to keep a dependency on Netty even when you need to include a different HTTP server.
Yes, you can use Spring MVC with Spring Boot. To create and run a Spring MVC web application in spring boot, you need to add the spring-boot-starter dependency in your pom. xml file.
Spring 5 includes Spring WebFlux, which provides reactive programming support for web applications. In this tutorial, we'll create a small reactive REST application using the reactive web components RestController and WebClient. We'll also look at how to secure our reactive endpoints using Spring Security.
It really depends what you are using Netty for. Assuming you are using it as an embedded HTTP server running on a separate port, you could simply initialise it within a Spring bean. I've achieved this in the past using a useful Netty/Atmosphere wrapper called Nettosphere:
@Service
public class NettyServer implements ServletContextAware {
private ServletContext servletContext;
private Nettosphere server;
@Autowired
private MyStatusHandler statusHandler;
@PostConstruct
public void initialiseNettyServer() {
String rootPath = servletContext.getContextPath() + "/api";
server = new Nettosphere.Builder().config(
new Config.Builder()
.host(SERVER_HOST)
.port(SERVER_PORT)
.resource(rootPath + "/status", statusHandler)
.build())
.build();
server.start();
}
@PreDestroy
public void shutdownNettyServer() {
server.stop();
}
}
This assumes the annotation-based configuration in Spring, you can easily achieve the same result using XML as explained in Jonathan's answer.
Of course, you may prefer to use Netty directly, in which case the same principle applies, but you will need to dig into the Netty user guide a bit to bootstrap the server correctly.
Just create a bean with start
and stop
methods that are responsible for starting up and shutting down the Netty server and then register the bean in the context with appropriate init and destroy hooks, e.g.:
<bean id="myNettyServer" class="x.y.z.MyNettyServer" init-method="start" destroy-method="shutdown"/>
Or alternatively use @PostConstruct
and @PreDestroy
annotations if you don't want to use XML configuration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With