编写反向代理中间件的时候需要一个应用两个Tomcat,具体实现场景如下:
一个虚拟机进程创建两个Tomcat容器:主Tomcat、从Tomcat。
主Tomcat:处理前端应用请求、websocket处理
从Tomcat:占用多个端口、处理多个反向代理请求。
LocalCache:双Tomcat共享数据、WebSocket会话信息
代码结构
pom.xml 引入
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
App启动类
@Component
public class App {
public static void main(String[] args) {
// 主Tomcat
SpringApplication.run(MasterApp.class, args);
// 从Tomcat
System.getProperties().put( "server.port", 8081);
SpringApplication.run(FollowApp.class, args);
}
}
主Tomcat启动类
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 主容器
* @author terry
* @version 1.0
* @date 2022/7/27 17:42
*/
@SpringBootApplication
public class MasterApp {
}
从Tomcat启动类
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* 从容器
* @author terry
* @version 1.0
* @date 2022/7/27 17:42
*/
@SpringBootApplication
// @EnableScheduling
public class FollowApp {
}
共享数据
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
/**
* 本地虚拟机缓存(用于双Tomcat共享数据)
* @author terry
* @version 1.0
* @date 2022/7/27 17:45
*/
public class LocalCache {
public final static Map<Integer, String> portProxy = new ConcurrentHashMap<>();
public final static BlockingQueue<Integer> portQueue = new ArrayBlockingQueue<>(100);
}
启动成功打印:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.2)
2022-07-27 18:01:35.790 INFO 18640 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-07-27 18:01:35.805 INFO 18640 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.2)
2022-07-27 18:01:36.883 INFO 18640 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2022-07-27 18:01:36.884 INFO 18640 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]