SpringBoot中动态注册接口

1. 说明

  • 接口注册,使用RequestMappingHandlerMapping来实现
  • mybatis中动态执行sql使用github上的SqlMapper工具类实现

2. 核心代码片段

        以下代码为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;}

3. 源码

3.1 核心代码

3.1.1 ApiServiceHandler

        handler中register职责如下:

  • 注册到数据库中
  • 注册接口到spring容器中
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);@Autowiredprivate RequestMappingHandlerMapping requestMappingHandlerMapping;@Autowired@Qualifier("sqlSessionFactory")private SqlSessionFactory sqlSessionFactory;@Autowiredprivate ApiServiceMapper apiServiceMapper;public void initialRegister() {List<ServiceDto> 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;}@ResponseBodypublic Response handler(HttpServletRequest request, HttpServletResponse response,@PathVariable(required = false) Map<String, Object> pathVariable,@RequestParam(required = false) Map<String, Object> requestParam,@RequestBody(required = false) Map<String, Object> 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<Map<String, Object>> result = sqlMapper.selectList(sql, params);return Response.ok(result);} catch (Exception e) {throw new CommonException("【公共查询异常】", e);}}/*** 查询所有在用接口** @return*/public List<ServiceDto> findApis() {return apiServiceMapper.findApis();}/*** 注册接口** @param path* @param sql* @return*/public boolean registerApiOfSql(String path, String sql) {try {return apiServiceMapper.insertApiSql(path, sql) > 0;} catch (Exception e) {throw new CommonException("【注册接口异常】插入sql配置失败", e);}}}

3.1.2 DynamicController

        手动注册接口执行/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 {@Autowiredprivate 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("接口注册失败");}
}

3.2 依赖类

3.2.1 SqlMapper

        此为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 <T>  泛型类型* @return*/private <T> T getOne(List<T> 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<String, Object> selectOne(String sql) {List<Map<String, Object>> list = selectList(sql);return getOne(list);}/*** 查询返回一个结果,多个结果时抛出异常** @param sql   执行的sql* @param value 参数* @return*/public Map<String, Object> selectOne(String sql, Object value) {List<Map<String, Object>> list = selectList(sql, value);return getOne(list);}/*** 查询返回一个结果,多个结果时抛出异常** @param sql        执行的sql* @param resultType 返回的结果类型* @param <T>        泛型类型* @return*/public <T> T selectOne(String sql, Class<T> resultType) {List<T> list = selectList(sql, resultType);return getOne(list);}/*** 查询返回一个结果,多个结果时抛出异常** @param sql        执行的sql* @param value      参数* @param resultType 返回的结果类型* @param <T>        泛型类型* @return*/public <T> T selectOne(String sql, Object value, Class<T> resultType) {List<T> list = selectList(sql, value, resultType);return getOne(list);}/*** 查询返回List<Map<String, Object>>** @param sql 执行的sql* @return*/public List<Map<String, Object>> selectList(String sql) {String msId = msUtils.select(sql);return sqlSession.selectList(msId);}/*** 查询返回List<Map<String, Object>>** @param sql   执行的sql* @param value 参数* @return*/public List<Map<String, Object>> selectList(String sql, Object value) {Class<?> parameterType = value != null ? value.getClass() : null;String msId = msUtils.selectDynamic(sql, parameterType);return sqlSession.selectList(msId, value);}/*** 查询返回指定的结果类型** @param sql        执行的sql* @param resultType 返回的结果类型* @param <T>        泛型类型* @return*/public <T> List<T> selectList(String sql, Class<T> resultType) {String msId;if (resultType == null) {msId = msUtils.select(sql);} else {msId = msUtils.select(sql, resultType);}return sqlSession.selectList(msId);}/*** 查询返回指定的结果类型** @param sql        执行的sql* @param value      参数* @param resultType 返回的结果类型* @param <T>        泛型类型* @return*/public <T> List<T> selectList(String sql, Object value, Class<T> resultType) {String msId;Class<?> parameterType = value != null ? value.getClass() : null;if (resultType == null) {msId = msUtils.selectDynamic(sql, parameterType);} else {msId = msUtils.selectDynamic(sql, parameterType, resultType);}return sqlSession.selectList(msId, value);}/*** 插入数据** @param sql 执行的sql* @return*/public int insert(String sql) {String msId = msUtils.insert(sql);return sqlSession.insert(msId);}/*** 插入数据** @param sql   执行的sql* @param value 参数* @return*/public int insert(String sql, Object value) {Class<?> parameterType = value != null ? value.getClass() : null;String msId = msUtils.insertDynamic(sql, parameterType);return sqlSession.insert(msId, value);}/*** 更新数据** @param sql 执行的sql* @return*/public int update(String sql) {String msId = msUtils.update(sql);return sqlSession.update(msId);}/*** 更新数据** @param sql   执行的sql* @param value 参数* @return*/public int update(String sql, Object value) {Class<?> parameterType = value != null ? value.getClass() : null;String msId = msUtils.updateDynamic(sql, parameterType);return sqlSession.update(msId, value);}/*** 删除数据** @param sql 执行的sql* @return*/public int delete(String sql) {String msId = msUtils.delete(sql);return sqlSession.delete(msId);}/*** 删除数据** @param sql   执行的sql* @param value 参数* @return*/public int delete(String sql, Object value) {Class<?> parameterType = value != null ? value.getClass() : null;String msId = msUtils.deleteDynamic(sql, parameterType);return sqlSession.delete(msId, value);}@Overridepublic void close() throws Exception {this.sqlSession.close();}private class MSUtils {private Configuration configuration;private LanguageDriver languageDriver;private MSUtils(Configuration configuration) {this.configuration = configuration;languageDriver = configuration.getDefaultScriptingLanuageInstance();}/*** 创建MSID** @param sql 执行的sql* @param sql 执行的sqlCommandType* @return*/private String newMsId(String sql, SqlCommandType sqlCommandType) {StringBuilder msIdBuilder = new StringBuilder(sqlCommandType.toString());msIdBuilder.append(".").append(sql.hashCode());return msIdBuilder.toString();}/*** 是否已经存在该ID** @param msId* @return*/private boolean hasMappedStatement(String msId) {return configuration.hasStatement(msId, false);}/*** 创建一个查询的MS** @param msId* @param sqlSource  执行的sqlSource* @param resultType 返回的结果类型*/private void newSelectMappedStatement(String msId, SqlSource sqlSource, final Class<?> resultType) {MappedStatement ms = new MappedStatement.Builder(configuration, msId, sqlSource, SqlCommandType.SELECT).resultMaps(new ArrayList<ResultMap>() {{add(new ResultMap.Builder(configuration, "defaultResultMap", resultType, new ArrayList<ResultMapping>(0)).build());}}).build();//缓存configuration.addMappedStatement(ms);}/*** 创建一个简单的MS** @param msId* @param sqlSource      执行的sqlSource* @param sqlCommandType 执行的sqlCommandType*/private void newUpdateMappedStatement(String msId, SqlSource sqlSource, SqlCommandType sqlCommandType) {MappedStatement ms = new MappedStatement.Builder(configuration, msId, sqlSource, sqlCommandType).resultMaps(new ArrayList<ResultMap>() {{add(new ResultMap.Builder(configuration, "defaultResultMap", int.class, new ArrayList<ResultMapping>(0)).build());}}).build();//缓存configuration.addMappedStatement(ms);}private String select(String sql) {String msId = newMsId(sql, SqlCommandType.SELECT);if (hasMappedStatement(msId)) {return msId;}StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);newSelectMappedStatement(msId, sqlSource, Map.class);return msId;}private String selectDynamic(String sql, Class<?> parameterType) {String msId = newMsId(sql + parameterType, SqlCommandType.SELECT);if (hasMappedStatement(msId)) {return msId;}SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);newSelectMappedStatement(msId, sqlSource, Map.class);return msId;}private String select(String sql, Class<?> resultType) {String msId = newMsId(resultType + sql, SqlCommandType.SELECT);if (hasMappedStatement(msId)) {return msId;}StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);newSelectMappedStatement(msId, sqlSource, resultType);return msId;}private String selectDynamic(String sql, Class<?> parameterType, Class<?> resultType) {String msId = newMsId(resultType + sql + parameterType, SqlCommandType.SELECT);if (hasMappedStatement(msId)) {return msId;}SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);newSelectMappedStatement(msId, sqlSource, resultType);return msId;}private String insert(String sql) {String msId = newMsId(sql, SqlCommandType.INSERT);if (hasMappedStatement(msId)) {return msId;}StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);newUpdateMappedStatement(msId, sqlSource, SqlCommandType.INSERT);return msId;}private String insertDynamic(String sql, Class<?> parameterType) {String msId = newMsId(sql + parameterType, SqlCommandType.INSERT);if (hasMappedStatement(msId)) {return msId;}SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);newUpdateMappedStatement(msId, sqlSource, SqlCommandType.INSERT);return msId;}private String update(String sql) {String msId = newMsId(sql, SqlCommandType.UPDATE);if (hasMappedStatement(msId)) {return msId;}StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);newUpdateMappedStatement(msId, sqlSource, SqlCommandType.UPDATE);return msId;}private String updateDynamic(String sql, Class<?> parameterType) {String msId = newMsId(sql + parameterType, SqlCommandType.UPDATE);if (hasMappedStatement(msId)) {return msId;}SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);newUpdateMappedStatement(msId, sqlSource, SqlCommandType.UPDATE);return msId;}private String delete(String sql) {String msId = newMsId(sql, SqlCommandType.DELETE);if (hasMappedStatement(msId)) {return msId;}StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);newUpdateMappedStatement(msId, sqlSource, SqlCommandType.DELETE);return msId;}private String deleteDynamic(String sql, Class<?> parameterType) {String msId = newMsId(sql + parameterType, SqlCommandType.DELETE);if (hasMappedStatement(msId)) {return msId;}SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);newUpdateMappedStatement(msId, sqlSource, SqlCommandType.DELETE);return msId;}}
}

3.2.2 ApiServiceMapper

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<ServiceDto> findApis();String findSqlByPath(@Param("path") String path);int insertApiSql(@Param("path") String path, @Param("sqlContent") String sqlContent);
}

3.2.3 ApiServiceMapper.xml

<?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="com.hz.pro.artifact.dynamic.mapper.main.ApiServiceMapper"><select id="findApis" resultType="com.hz.pro.artifact.dynamic.bean.ServiceDto">select path, sql_content from t_api_sql where in_use = 1</select><select id="findSqlByPath" resultType="java.lang.String">select sql_content from t_api_sql where path = #{path} and in_use = 1</select><insert id="insertApiSql">INSERT INTO t_api_sql VALUES(#{path}, #{sqlContent}, 1)</insert></mapper>

4 效果

4.1 注册

4.2 查询

5. 其他

       上述实现步骤已完成接口的注册、查询功能。但是存在一个问题,重启后接口便不存在了,需要重新初始化。后续可以使用监听读取数据库中接口配置进行接口的初始化。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/324931.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

鸿蒙应用中的通知

目录 1、通知流程 2、发布通知 2.1、发布基础类型通知 2.1.1、接口说明 2.1.2、普通文本类型通知 2.1.3、长文本类型通知 2.1.4、多行文本类型通知 2.1.5、图片类型通知 2.2、发布进度条类型通知 2.2.1、接口说明 2.2.2、示例 2.3、为通知添加行为意图 2.3.1、接…

Linux——系统安全及应用

一、基本安全措施 1、系统账号清理 常见的非登录用户账号包括bin、daemon、 adm、lp、mail等。为了确保系统安全&#xff0c;这些用户账号的登录Shell通常是/ sbin/nologin&#xff0c;表示禁止终端登录&#xff0c;应确保不被人为改动。 //将非登陆用户的Shell设为/sbin/nolo…

sqlserver把Long类型的时间转换为可视化的时间

SqlServer 把Long类型日期还原yyyy-MM-dd HH:mm:ss格式日期&#xff1a; SELECT CONVERT(DATETIME, Dateadd(second, 1704330940847 / 1000, 19700101 08:00), 111) AS tt SqlServer 把Long类型日期还原yyyy-MM-dd格式日期&#xff1a; SqlServer中&#xff0c;按照UTC计算标准…

Prometheus插件安装(cadvisor)

简介 当docker服务数量到一定程度&#xff0c;为了保证系统的文档&#xff0c;我们就需要对docker进行监控。一般情况下我们可以通过docker status命令来做简单的监控&#xff0c;但是无法交给prometheus采集&#xff0c;因此谷歌的cadvisor诞生了。cadvisor不仅可以轻松收集到…

深度学习中的准确率、精确率(查准率)、召回率(查全率)、F1值、ROC曲线的AUC值,

混淆矩阵 其中关于 TP, TN; FP, FN 的解释&#xff1b; 其中首字母 T&#xff0c;F代表预测的情况&#xff0c;即T代表预测的结果是对的&#xff0c; F代表预测的结果是错误的&#xff1b; 第二个字母代表预测是预测为 正样本&#xff0c;还是负样本&#xff0c; Positve 代表…

西电期末1021.梅森尼数

一.题目 二.分析与思路 用pow函数计算&#xff0c;编写布尔函数&#xff0c;用定义判断&#xff0c;因为不知道有没有时间限制&#xff0c;可能会超时&#xff0c;此时可以用素数筛。 三.代码实现 #include<bits/stdc.h> bool f(int m){for(int i2;i<m-1;i){if(m%i0…

Vue-3、模板语法

1、插值语法 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>模板语法</title><!--引入vue--><script type"text/javascript" src"https://cdn.jsdelivr.net/npm/vue2…

ROS学习笔记(7)进一步深入了解ROS第一步

0.前提 最近在学习宾夕法尼亚大学工程学院的ROS公开课&#xff0c;在尽力的去融入全英语的环境&#xff08;哪怕我的英语水准并不是很高&#xff09;。既然是在学习&#xff0c;笔记也就是必须的了&#xff0c;当然这些笔记都是课程当中提出的问题&#xff0c;我去寻找后得出的…

三款推荐的 FTP 工具

&#x1f947; 版权: 本文由【墨理学AI】原创、在CSDN首发、各位大佬、敬请查阅&#x1f389; 声明: 作为全网 AI 领域 干货最多的博主之一&#xff0c;❤️ 不负光阴不负卿 ❤️ 文章目录 三款推荐的 FTP 工具filezillawinscpFinalShell SSHXftp❤️ 人生苦短&#xff0c; 欢迎…

利用小红书笔记详情API:为内容运营提供强大的支持

利用小红书笔记详情API&#xff0c;内容运营者可以获得对小红书平台上的笔记内容的深入洞察&#xff0c;从而为其运营工作提供强大的支持。以下是该API如何支持内容运营的几个关键方面&#xff1a; 获取笔记内容与数据&#xff1a; API允许内容运营者直接获取小红书平台上的笔记…

阿里云服务器 使用Certbot申请免费 HTTPS 证书及自动续期

前言 Certbot是一款免费且开源的自动化安全证书管理工具&#xff0c;由电子前沿基金会&#xff08;EFF&#xff09;开发和维护&#xff0c;是在Linux、Apache和Nginx服务器上配置和管理SSL/TLS证书的一种机制。Certbot可以自动完成域名的认证并安装证书。 一、 安装软件 1.1…

如何找到各行业的企业名录?分享三种方法!

企业拓客中一定会遇到的问题&#xff1a;如何找到各个行业的企业名录&#xff1f; 今天分享三种查找企业联系方式的方法。 一、网络关键词查询 1. 如果你想查找某个地区的所有企业名录&#xff0c;可以输入&#xff1a;上海 制造业 企业名录 filetype:xls intitle:上海。&a…