在上节的文章中<用Servlet写简单的ApiGateway (一)>
使用Servlet实现了最基本的反向代理, 为了让下一章更容易理解, 本章主要介绍Mybatis组件在APIGateway项目中的应用
一, 环境准备
1. 上节文章介绍的APIGateway项目
2. 安装Mysql
3. 准备数据
Create table routeinfo(
id int(10) not null auto_increment primary key,
isDisabled int(1) not null,
clientUrl varchar(100) not null,
serviceUrl varchar(100) not null,
userCreate varchar(20) not null,
dateCreate date not null,
userUpdate varchar(20),
dateUpdate date
);
insert into routeinfo (isDisabled,clientUrl,serviceUrl,userCreate,dateCreate) values(0,'/servlet-demo/App','serviceUrl/App','sys',sysdate());
insert into routeinfo (isDisabled,clientUrl,serviceUrl,userCreate,dateCreate) values(0,'/api-gateway-demo/App','serviceUrl/App','sys',sysdate());
commit;
PS: 为了更容易理解, 我重命名了上节文章的项目
操作如下:
1. 在workspaces复制一份source code
2. 更改一下文件:
.project文件和pom.xml文件
导入到workspaces
二, 添加mysql驱动和Mybatis组件的依赖
pom.xml文件
在dependencies节点添加以下代码:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.9-rc</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
三, 配置Mybatis
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/demo"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="resources/RouteInfoMapper.xml"/>
</mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="resources.RouteInfoMapper">
<select id="getAll" resultType="com.demo.models.RouteInfo">
select * from RouteInfo
</select>
<select id="getByUrl" resultType="com.demo.models.RouteInfo">
select * from RouteInfo where clientUrl=#{clientUrl}
</select>
</mapper>
四, 添加数据操作类RouteInfoDataAccess和数据实体RouteInfo和主程序App
package com.demo.data;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.demo.apigateway.App;
import com.demo.models.RouteInfo;
public class RouteInfoDataAccess {
public RouteInfoDataAccess() {
}
private SqlSession session;
public List<RouteInfo> getAllRouteInfo() {
List<RouteInfo> routes = null;
InputStream is = RouteInfoDataAccess.class.getClassLoader().getResourceAsStream("resources/mybatis-config.xml");
try {
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
session = sessionFactory.openSession();
routes = session.selectList("resources.RouteInfoMapper.getAll");
} catch (Exception ex) {
}
return routes;
}
public String getRouteInfo(String clientUrl) {
String serviceUrl = null;
InputStream is = App.class.getClassLoader().getResourceAsStream("resources/my-batis.xml");
try {
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
session = sessionFactory.openSession();
RouteInfo ri = session.selectOne("resources.RouteInfoMapper.getByUrl", clientUrl);
serviceUrl=ri.serviceUrl;
} catch (Exception ex) {
serviceUrl = ex.toString()+" error detected.";
}
return serviceUrl;
}
}
package com.demo.models;
public class RouteInfo {
public String clientUrl;
public int id;
public String httpMethod;
}
package com.demo.apigateway;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import com.demo.data.RouteInfoDataAccess;
public class App extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void init() throws ServletException {
}
@Override
public void destroy() {
// 什么也不做
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RouteInfoDataAccess routeData = new RouteInfoDataAccess();
String clientUrl = request.getRequestURI();
String serviceUrl = routeData.getRouteInfo(clientUrl);
// HttpClient client = HttpClients.createDefault();
// HttpGet httpGet = new HttpGet(url);
//
// HttpResponse httpResponse = client.execute(httpGet);
// InputStream inStream = httpResponse.getEntity().getContent();
// BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8")); // utf-8 encoded
// StringBuilder strber = new StringBuilder();
// String line = null;
// while ((line = reader.readLine()) != null)
// strber.append(line);
//
// inStream.close();
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
// out.println(strber.toString());
out.println(String.format("client url: %s, service url: %s",clientUrl, serviceUrl));
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
五, 测试
运行效果如下:
总结:
利用Mybatis和mysql把路由数据储存在数据库, 就可以实现路由的注册和服务转发.
下篇预告:
用Servlet实现简单的APIGateway (二) -- 路由注册和服务转发