暴露服务
- 服务之间的通信协议采用http协议,所以在服务provider中启动tomcat暴露服务
- 添加内嵌tomcat的依赖
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.12</version>
</dependency>
</dependencies>
public class HttpServer {
/**
* tomca t服务启动
* 参考tomcat配置
* <Server port= "8005" shutdown="SHUTDOWN">
* <Service name="Catalina">
* <Connector port="8080" protocol="HTTP/1.1"
* connectionTimeout="20000"
* redirectPort="8443"
* URIEncoding="UTF-8"/>
* <Engine name="Catalina" defaultHost="localhost"/>
* <Host name="localhost" appBase="webapps"
* unpackWARs= "true" autoDeploy="true">
* <Context path="" doBase= "WORKDIR" reloadable="true"/>
* </Host>
* </Engine>
* </Service>
* </Server>
*/
public void start(String hostname,int port){
//实例一个tomcat
Tomcat tomcat=new Tomcat();
//构建一个server
Server server=tomcat.getServer();
//构建service
Service service = tomcat.getService();
//获取service
Connector connector = new Connector();
connector.setPort(port);
connector.setURIEncoding("UTF-8");
//构建Engine
Engine engine = new StandardEngine();
//构建host
Host host = new StandardHost();
//构建Context
String contextPath="";
Context context = new StandardContext();
context.setPath(contextPath);
context.addLifecycleListener(new Tomcat.FixContextListener());//生命周期监听器
//然后按照server.xml,一层层把子节点添加到父节点
host.addChild(context);
engine.addChild(context);
service.setContainer(engine);
service.addConnector(connector);
//service在getServer时就被添加到Server节点了
//tomcat是一个servlet,设置路径与映射
tomcat.addServlet(contextPath,"dispatcher",new DispatcherServlet());
context.addServletMappingDecoded("/*","dispatcher");
try{
tomcat.start();//启动tomcat
tomcat.getServer().await();//接受请求
} catch (LifecycleException e) {
e.printStackTrace();
}
}
}
public class DispatcherServlet extends HttpServlet {
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//HttpServerHandler是真正处理远程调用请求的
new HttpServerHandler().handler(req,resp);
}
}
- HttpServerHandler处理远程调用请求
public class HttpServerHandler {
public void handler(HttpServletRequest req, HttpServletResponse resp){
try{
//服务器的处理逻辑
//1.通过请求流获取请求服务调用的参数
InputStream inputStream=req.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Invocation invocation = (Invocation) objectInputStream.readObject();
//2.从注册中心获取服务列表
Class implClass = NativeRegistry.get(new URL("localhost",8080),invocation.getInterfaceName());
//3.调用服务 反射
Method method = implClass.getMethod(invocation.getMethodName(), invocation.getParamTypes());
String result = (String) method.invoke(implClass.newInstance(), invocation.getParams());
//4.结果返回
IOUtils.write(result,resp.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
}