[JAVA] Spring Boot application built-in Tomcat, Apache and WebSocket integration

About Spring Boot applications

When creating a web application with SpringBoot, it is possible to start it by executing the artifact of the Jar file using the built-in Tomcat.

java -jar xxx.jar

However, since it is different from the conventional deployment with War file, I was addicted to the setting of cooperation with the built-in Tomcat + Apache + WebSocket.

Ajp settings

Add JavaConfig for embedded tomcat

The following JavaConfig will be the same as the traditional server.xml settings.

TomcatConfiguration.java


@Configuration
public class TomcatConfiguration 
{

 
    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
                TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.addAdditionalTomcatConnectors(ajpConnector());
        return tomcat;
    }

    private Connector ajpConnector() {
        Connector connector = new Connector("org.apache.coyote.ajp.AjpNioProtocol");
        connector.setAttribute("maxThreads", 100);
        connector.setProtocol("AJP/1.3");
        connector.setPort(8009);
        connector.setRedirectPort(8043);
        connector.setURIEncoding("UTF-8");
        return connector;
    }

}

server.xml


<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

Enable WebSocket

1. Add dependency

Add to gradle dependency

build.gradle


dependencies {
...
    compile "org.springframework.boot:spring-boot-starter-websocket:1.3.3.RELEASE"
...
}

2. Enable Websocket

Add and enable the @EnableWebSocketMessageBroker annotation

Application.java


@SpringBootApplication
@EnableWebSocketMessageBroker//add to
public class Application extends SpringBootServletInitializer
{
    public static void main( String... args )
    {
         SpringApplication.run( Application.class, args );
    }
}

3. Added JavaConfig for WebSocket

WebSocketConfiguration.java


@Configuration
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer { //Inherit AbstractWebSocketMessageBrokerConfigurer and customize WebSocket related bean definition

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat").setAllowedOrigins("*").withSockJS();//Endpoints subscribed to by the front desk
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/sock");
        registry.enableSimpleBroker("/topic", "/queue");
    }
}

4. Controller settings

ChatController.java


@RestController
@RequestMapping("/chat/")
public class ChatController
{    
    @MessageMapping( "/chat/{accountId}" )
    @SendTo( "/topic/chat/all" )
    public ChatList all( @DestinationVariable Integer accountId, ChatMessage message ) throws InterruptedException
    {
    ...
    }

}

5. Front side SockJS settings

This time we use Angular Js1 system

ChatService.js


import SockJS from "sockjs-client";

export function ChatService($http, ChatStore) {
  let stompClient = {};
  var connect = ( $scope ) => {
    let socket = new SockJS( '/chat');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, (frame) => {//WebSocket connection establishment
      stompClient.subscribe('/topic/chat/all', ( chatList ) => {
      ...
      });
    });
  }
  var send = () => {
    stompClient.send(`/sock/chat/${ChatStore.accountId}`, {},JSON.stringify({
      'value': ChatStore.message
    }));
  }
  return {
    connect,
    send
 };
}

Apache settings

httpd.conf


ProxyPass /chat/info ajp://localhost:8009/chat/info #URL that connects SockJS and WebSocket automatically generated by SpringWebSocket
ProxyPass /chat ws://localhost:8080/chat #ws proxy settings
ProxyPass / ajp://localhost:8009/ #ajp proxy settings

Operation check

With the above settings, the built-in Tomcat + Apache + WebSocket will work (should) work! !!

At the end

I've folded everything except the main points, but please forgive me as I will revise the article each time there is a mistake. .. .. orz

Well then.

Recommended Posts

Spring Boot application built-in Tomcat, Apache and WebSocket integration
Spring Boot 2.0.0 does not start built-in tomcat
Apache and tomcat
Spring Boot 2.3 Application Availability
[Spring Boot] Web application creation
CICS-Run Java application-(4) Spring Boot application
Implement REST API with Spring Boot and JPA (Application Layer)
Spring Boot application development in Eclipse
Spring Boot application code review points
Inquiry application creation with Spring Boot
Spring profile function, and Spring Boot application.properties
Implement Spring Boot application in Gradle
[Java] LINE integration with Spring Boot
[Spring Boot] Precautions when developing a web application with Spring Boot and placing war on an independent Tomcat server
Deploy the WEB application by Spring Boot to Tomcat server as WAR
Processing at application startup with Spring Boot
HTTPS with Spring Boot and Let's Encrypt
Start web application development with Spring Boot
Launch Nginx + Spring Boot application with docker-compose
Try Spring Boot 1 (Environment construction ~ Tomcat startup)
Add spring boot and gradle to eclipse
Run WEB application with Spring Boot + Thymeleaf
About designing Spring Boot and unit test environment
Spring Boot Whitelabel Error Page and JSON Response
Configure Spring Boot application with maven multi module
How to use built-in h2db with spring boot
Output request and response log in Spring Boot
Create a Spring Boot application using IntelliJ IDEA
Various correspondence table of Spring Framework and Spring Boot
[Raspberry Pi] Try to link Apache2 and Tomcat
Deploy a Spring Boot application on Elastic Beanstalk
CSRF countermeasure policy and implementation example in REST application using "Spring Boot" + "EXT JS"