以下代码为spring动态注册接口代码示例
@Autowired
private RequestMappingHandlerMapping requestMappingHandlerMapping;
public boolean register2Spring(String path) {
RequestMappingInfo requestMappingInfo = RequestMappingInfo.paths(path)
.methods(RequestMethod.POST)
.produces(MediaType.APPLICATION_JSON_VALUE)
.options(requestMappingHandlerMapping.getBuilderConfiguration())
.build();
Method method = ReflectionUtils.findMethod(getClass(), "handler",
HttpServletRequest.class, HttpServletResponse.class,
Map.class, Map.class, Map.class);
boolean status = true;
try {
requestMappingHandlerMapping.registerMapping(requestMappingInfo, this, method);
LOGGER.info("【接口注册成功】{}", path);
} catch (Exception e) {
status = false;
LOGGER.error("【注册接口异常】动态映射失败", e.getMessage());
}
return status;
}
handler中register职责如下:
import com.alibaba.fastjson2.JSONObject;
import com.google.common.net.HttpHeaders;
import com.hz.pro.artifact.bean.CommonException;
import com.hz.pro.artifact.bean.Response;
import com.hz.pro.artifact.dynamic.bean.ServiceDto;
import com.hz.pro.artifact.dynamic.mapper.main.ApiServiceMapper;
import com.hz.pro.artifact.utils.SqlMapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
* @author pp_lan
* @date 2024/1/4
*/
@Service
public class ApiServiceHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ApiServiceHandler.class);
@Autowired
private RequestMappingHandlerMapping requestMappingHandlerMapping;
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
@Autowired
private ApiServiceMapper apiServiceMapper;
public void initialRegister() {
List apis = findApis();
for (ServiceDto api : apis) {
try {
register2Spring(api.getPath());
} catch (Exception e) {
LOGGER.error("[接口注册失败]{}", api.getPath(), e.getMessage());
}
}
}
/**
* 注册到spring,并添加到数据库中
*
* @param path
* @param sql
* @return
*/
public boolean register(String path, String sql) {
boolean status = this.registerApiOfSql(path, sql);
if (status) {
status = register2Spring(path);
}
return status;
}
/**
* 注册到容器
*
* @param path
* @return
*/
public boolean register2Spring(String path) {
RequestMappingInfo requestMappingInfo = RequestMappingInfo.paths(path)
.methods(RequestMethod.POST)
.produces(MediaType.APPLICATION_JSON_VALUE)
.options(requestMappingHandlerMapping.getBuilderConfiguration())
.build();
Method method = ReflectionUtils.findMethod(getClass(), "handler",
HttpServletRequest.class, HttpServletResponse.class,
Map.class, Map.class, Map.class);
boolean status = true;
try {
requestMappingHandlerMapping.registerMapping(requestMappingInfo, this, method);
LOGGER.info("【接口注册成功】{}", path);
} catch (Exception e) {
status = false;
LOGGER.error("【注册接口异常】动态映射失败", e.getMessage());
}
return status;
}
@ResponseBody
public Response handler(HttpServletRequest request, HttpServletResponse response,
@PathVariable(required = false) Map pathVariable,
@RequestParam(required = false) Map requestParam,
@RequestBody(required = false) Map requestBody) {
String header = request.getHeader(HttpHeaders.CONTENT_TYPE);
// 参数处理
JSONObject params;
if (header != null && header.contains(MediaType.APPLICATION_JSON_VALUE)) {
params = new JSONObject(requestBody);
} else {
params = new JSONObject(requestParam);
}
// 执行查询
try (SqlMapper sqlMapper = new SqlMapper(sqlSessionFactory)) {
String path = request.getRequestURI();
String sql = apiServiceMapper.findSqlByPath(path);
List
手动注册接口执行/dynamic/register方法,便可以完成接口注册。
import com.hz.pro.artifact.bean.Response;
import com.hz.pro.artifact.dynamic.bean.ApiReq;
import com.hz.pro.artifact.dynamic.service.ApiServiceHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author pp_lan
* @date 2024/1/2
*/
@RestController
@RequestMapping("/dynamic")
public class DynamicController {
@Autowired
private ApiServiceHandler apiServiceHandler;
/**
* 注册接口
*
* @param apiReq
* @return
*/
@PostMapping("register")
public Response register(@RequestBody @Validated ApiReq apiReq) {
boolean registerStatus = apiServiceHandler.register(apiReq.getPath(), apiReq.getSql());
return registerStatus ? Response.ok("接口注册成功") : Response.error("接口注册失败");
}
}
此为github上有开源工具类,最新代码请移步github。以下为其源码:
import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* MyBatis执行sql工具,在写SQL的时候建议使用参数形式的可以是${}或#{}
*
* 不建议将参数直接拼到字符串中,当大量这么使用的时候由于缓存MappedStatement而占用更多的内存
*
* @author liuzh
* @since 2015-03-10
*/
public class SqlMapper implements AutoCloseable {
private final MSUtils msUtils;
private final SqlSession sqlSession;
/**
* 构造方法,默认缓存MappedStatement
*
* @param sqlSession
*/
public SqlMapper(SqlSession sqlSession) {
this.sqlSession = sqlSession;
this.msUtils = new MSUtils(sqlSession.getConfiguration());
}
public SqlMapper(SqlSessionFactory sqlSessionFactory) {
this.sqlSession = sqlSessionFactory.openSession();
this.msUtils = new MSUtils(sqlSession.getConfiguration());
}
/**
* 获取List中最多只有一个的数据
*
* @param list List结果
* @param 泛型类型
* @return
*/
private T getOne(List list) {
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 1) {
throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
return null;
}
}
/**
* 查询返回一个结果,多个结果时抛出异常
*
* @param sql 执行的sql
* @return
*/
public Map selectOne(String sql) {
List
import com.hz.pro.artifact.dynamic.bean.ServiceDto;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author pp_lan
* @date 2024/1/5
*/
public interface ApiServiceMapper {
List findApis();
String findSqlByPath(@Param("path") String path);
int insertApiSql(@Param("path") String path, @Param("sqlContent") String sqlContent);
}
INSERT INTO t_api_sql VALUES(#{path}, #{sqlContent}, 1)
5. 其他
上述实现步骤已完成接口的注册、查询功能。但是存在一个问题,重启后接口便不存在了,需要重新初始化。后续可以使用监听读取数据库中接口配置进行接口的初始化。