code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
package zack.gateway.center.domain.operation.model.vo; /** * @author zack * @description 应用服务 VO */ public class ApplicationSystemDataVO { /** 系统标识 */ private String systemId; /** 系统名称 */ private String systemName; /** 系统类型;RPC、HTTP*/ private String systemType; /** 注册中心;zookeeper://127.0.0.1:2181*/ private String systemRegistry; public ApplicationSystemDataVO() { } public ApplicationSystemDataVO(String systemId, String systemName) { this.systemId = systemId; this.systemName = systemName; } public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public String getSystemName() { return systemName; } public void setSystemName(String systemName) { this.systemName = systemName; } public String getSystemType() { return systemType; } public void setSystemType(String systemType) { this.systemType = systemType; } public String getSystemRegistry() { return systemRegistry; } public void setSystemRegistry(String systemRegistry) { this.systemRegistry = systemRegistry; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/domain/operation/model/vo/ApplicationSystemDataVO.java
Java
mit
1,295
package zack.gateway.center.domain.operation.model.vo; import java.util.Date; /** * @author zack * @description 网关分配 */ public class GatewayDistributionDataVO { /** 自增主键 */ private Integer id; /** 分组标识 */ private String groupId; /** 网关标识 */ private String gatewayId; /** 系统标识 */ private String systemId; /** 系统名称 */ private String systemName; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; public GatewayDistributionDataVO() { } public GatewayDistributionDataVO(String groupId, String gatewayId) { this.groupId = groupId; this.gatewayId = gatewayId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getGatewayId() { return gatewayId; } public void setGatewayId(String gatewayId) { this.gatewayId = gatewayId; } public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public String getSystemName() { return systemName; } public void setSystemName(String systemName) { this.systemName = systemName; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/domain/operation/model/vo/GatewayDistributionDataVO.java
Java
mit
1,818
package zack.gateway.center.domain.operation.model.vo; /** * @author zack * @description 网关服务 */ public class GatewayServerDataVO { /** 自增主键 */ private Integer id; /** 分组标识 */ private String groupId; /** 分组名称 */ private String groupName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/domain/operation/model/vo/GatewayServerDataVO.java
Java
mit
734
package zack.gateway.center.domain.operation.model.vo; import java.util.Date; /** * @author zack * @description 网关服务明细 */ public class GatewayServerDetaiDatalVO { /** 自增ID */ private Integer id; /** 分组标识 */ private String groupId; /** 网关标识 */ private String gatewayId; /** 网关名称 */ private String gatewayName; /** 网关地址 */ private String gatewayAddress; /** 服务状态 */ private Integer status; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; public GatewayServerDetaiDatalVO() { } public GatewayServerDetaiDatalVO(String groupId, String gatewayId) { this.groupId = groupId; this.gatewayId = gatewayId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getGatewayId() { return gatewayId; } public void setGatewayId(String gatewayId) { this.gatewayId = gatewayId; } public String getGatewayName() { return gatewayName; } public void setGatewayName(String gatewayName) { this.gatewayName = gatewayName; } public String getGatewayAddress() { return gatewayAddress; } public void setGatewayAddress(String gatewayAddress) { this.gatewayAddress = gatewayAddress; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/domain/operation/model/vo/GatewayServerDetaiDatalVO.java
Java
mit
2,064
package zack.gateway.center.domain.operation.repository; import zack.gateway.center.domain.operation.model.vo.*; import zack.gateway.center.infrastructure.common.OperationRequest; import java.util.List; /** * @author zack * @description 运营数据查询仓储服务 */ public interface IDataOperationManageRepository { List<GatewayServerDataVO> queryGatewayServerListByPage(OperationRequest<String> request); int queryGatewayServerListCountByPage(OperationRequest<String> request); List<ApplicationSystemDataVO> queryApplicationSystemListByPage(OperationRequest<ApplicationSystemDataVO> request); int queryApplicationSystemListCountByPage(OperationRequest<ApplicationSystemDataVO> request); List<ApplicationInterfaceDataVO> queryApplicationInterfaceListByPage(OperationRequest<ApplicationInterfaceDataVO> request); int queryApplicationInterfaceListCountByPage(OperationRequest<ApplicationInterfaceDataVO> request); List<ApplicationInterfaceMethodDataVO> queryApplicationInterfaceMethodListByPage(OperationRequest<ApplicationInterfaceMethodDataVO> request); int queryApplicationInterfaceMethodListCountByPage(OperationRequest<ApplicationInterfaceMethodDataVO> request); List<GatewayServerDetaiDatalVO> queryGatewayServerDetailListByPage(OperationRequest<GatewayServerDetaiDatalVO> request); int queryGatewayServerDetailListCountByPage(OperationRequest<GatewayServerDetaiDatalVO> request); List<GatewayDistributionDataVO> queryGatewayDistributionListByPage(OperationRequest<GatewayDistributionDataVO> request); int queryGatewayDistributionListCountByPage(OperationRequest<GatewayDistributionDataVO> request); }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/domain/operation/repository/IDataOperationManageRepository.java
Java
mit
1,682
package zack.gateway.center.domain.operation.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import zack.gateway.center.application.IDataOperationManageService; import zack.gateway.center.domain.operation.model.vo.*; import zack.gateway.center.domain.operation.repository.IDataOperationManageRepository; import zack.gateway.center.infrastructure.common.OperationRequest; import zack.gateway.center.infrastructure.common.OperationResult; import javax.annotation.Resource; import java.util.List; /** * @author zack * @description 网关运营数据管理 */ @Service public class DataOperationManageService implements IDataOperationManageService { private Logger logger = LoggerFactory.getLogger(DataOperationManageService.class); @Resource private IDataOperationManageRepository repository; @Override public OperationResult<GatewayServerDataVO> queryGatewayServer(OperationRequest<String> request) { List<GatewayServerDataVO> list = repository.queryGatewayServerListByPage(request); int count = repository.queryGatewayServerListCountByPage(request); return new OperationResult<>(count, list); } @Override public OperationResult<ApplicationSystemDataVO> queryApplicationSystem(OperationRequest<ApplicationSystemDataVO> request) { List<ApplicationSystemDataVO> list = repository.queryApplicationSystemListByPage(request); int count = repository.queryApplicationSystemListCountByPage(request); return new OperationResult<>(count, list); } @Override public OperationResult<ApplicationInterfaceDataVO> queryApplicationInterface(OperationRequest<ApplicationInterfaceDataVO> request) { List<ApplicationInterfaceDataVO> list = repository.queryApplicationInterfaceListByPage(request); int count = repository.queryApplicationInterfaceListCountByPage(request); return new OperationResult<>(count, list); } @Override public OperationResult<ApplicationInterfaceMethodDataVO> queryApplicationInterfaceMethod(OperationRequest<ApplicationInterfaceMethodDataVO> request) { List<ApplicationInterfaceMethodDataVO> list = repository.queryApplicationInterfaceMethodListByPage(request); int count = repository.queryApplicationInterfaceMethodListCountByPage(request); return new OperationResult<>(count, list); } @Override public OperationResult<GatewayServerDetaiDatalVO> queryGatewayServerDetail(OperationRequest<GatewayServerDetaiDatalVO> request) { List<GatewayServerDetaiDatalVO> list = repository.queryGatewayServerDetailListByPage(request); int count = repository.queryGatewayServerDetailListCountByPage(request); return new OperationResult<>(count, list); } @Override public OperationResult<GatewayDistributionDataVO> queryGatewayDistribution(OperationRequest<GatewayDistributionDataVO> request) { List<GatewayDistributionDataVO> list = repository.queryGatewayDistributionListByPage(request); int count = repository.queryGatewayDistributionListCountByPage(request); return new OperationResult<>(count, list); } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/domain/operation/service/DataOperationManageService.java
Java
mit
3,210
package zack.gateway.center.domain.register.model.vo; /** * @author zack * @description 接口方法 VO */ public class ApplicationInterfaceMethodVO { /** 系统标识 */ private String systemId; /** 接口标识 */ private String interfaceId; /** 方法标识 */ private String methodId; /** 方法名称 */ private String methodName; /** 参数类型(RPC 限定单参数注册);new String[]{"java.lang.String"}、new String[]{"cn.bugstack.gateway.rpc.dto.XReq"} */ private String parameterType; /** 网关接口 */ private String uri; /** 接口类型;GET、POST、PUT、DELETE */ private String httpCommandType; /** 是否鉴权;true = 1是、false = 0否 */ private Integer auth; public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public String getInterfaceId() { return interfaceId; } public void setInterfaceId(String interfaceId) { this.interfaceId = interfaceId; } public String getMethodId() { return methodId; } public void setMethodId(String methodId) { this.methodId = methodId; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public String getParameterType() { return parameterType; } public void setParameterType(String parameterType) { this.parameterType = parameterType; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getHttpCommandType() { return httpCommandType; } public void setHttpCommandType(String httpCommandType) { this.httpCommandType = httpCommandType; } public Integer getAuth() { return auth; } public void setAuth(Integer auth) { this.auth = auth; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/domain/register/model/vo/ApplicationInterfaceMethodVO.java
Java
mit
2,048
package zack.gateway.center.domain.register.model.vo; /** * @author zack * @description 应用接口 VO */ public class ApplicationInterfaceVO { /** 系统标识 */ private String systemId; /** 接口标识 */ private String interfaceId; /** 接口名称 */ private String interfaceName; /** 接口版本 */ private String interfaceVersion; public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public String getInterfaceId() { return interfaceId; } public void setInterfaceId(String interfaceId) { this.interfaceId = interfaceId; } public String getInterfaceName() { return interfaceName; } public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } public String getInterfaceVersion() { return interfaceVersion; } public void setInterfaceVersion(String interfaceVersion) { this.interfaceVersion = interfaceVersion; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/domain/register/model/vo/ApplicationInterfaceVO.java
Java
mit
1,097
package zack.gateway.center.domain.register.model.vo; /** * @author zack * @description 应用服务 VO */ public class ApplicationSystemVO { /** 系统标识 */ private String systemId; /** 系统名称 */ private String systemName; /** 系统类型;RPC、HTTP*/ private String systemType; /** 注册中心;zookeeper://127.0.0.1:2181*/ private String systemRegistry; public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public String getSystemName() { return systemName; } public void setSystemName(String systemName) { this.systemName = systemName; } public String getSystemType() { return systemType; } public void setSystemType(String systemType) { this.systemType = systemType; } public String getSystemRegistry() { return systemRegistry; } public void setSystemRegistry(String systemRegistry) { this.systemRegistry = systemRegistry; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/domain/register/model/vo/ApplicationSystemVO.java
Java
mit
1,092
package zack.gateway.center.domain.register.repository; import zack.gateway.center.domain.register.model.vo.ApplicationInterfaceMethodVO; import zack.gateway.center.domain.register.model.vo.ApplicationInterfaceVO; import zack.gateway.center.domain.register.model.vo.ApplicationSystemVO; /** * @author zack * @description 接口注册仓储服务 */ public interface IRegisterManageRepository { void registerApplication(ApplicationSystemVO applicationSystemVO); void registerApplicationInterface(ApplicationInterfaceVO applicationInterfaceVO); void registerApplicationInterfaceMethod(ApplicationInterfaceMethodVO applicationInterfaceMethodVO); }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/domain/register/repository/IRegisterManageRepository.java
Java
mit
671
package zack.gateway.center.domain.register.service; import org.springframework.stereotype.Service; import zack.gateway.center.application.IRegisterManageService; import zack.gateway.center.domain.register.model.vo.ApplicationInterfaceMethodVO; import zack.gateway.center.domain.register.model.vo.ApplicationInterfaceVO; import zack.gateway.center.domain.register.model.vo.ApplicationSystemVO; import zack.gateway.center.domain.register.repository.IRegisterManageRepository; import javax.annotation.Resource; /** * @author zack * @description 接口注册服务 */ @Service public class IRegisterManageServiceImpl implements IRegisterManageService { @Resource private IRegisterManageRepository registerManageRepository; @Override public void registerApplication(ApplicationSystemVO applicationSystemVO) { registerManageRepository.registerApplication(applicationSystemVO); } @Override public void registerApplicationInterface(ApplicationInterfaceVO applicationInterfaceVO) { registerManageRepository.registerApplicationInterface(applicationInterfaceVO); } @Override public void registerApplicationInterfaceMethod(ApplicationInterfaceMethodVO applicationInterfaceMethodVO) { registerManageRepository.registerApplicationInterfaceMethod(applicationInterfaceMethodVO); } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/domain/register/service/IRegisterManageServiceImpl.java
Java
mit
1,353
/** * @description 应用管理 * @author zack */ package zack.gateway.center.domain.utilize;
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/domain/utilize/package-info.java
Java
mit
100
package zack.gateway.center.infrastructure.common; /** * @author zack * @description 基础信息 */ public class Constants { public static final class GatewayStatus { // 0;不可用 public static final Integer NotAvailable = 0; // 1; 可使用 public static final Integer Available = 1; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/common/Constants.java
Java
mit
344
package zack.gateway.center.infrastructure.common; import org.apache.commons.lang3.StringUtils; public class OperationRequest<T> { private int pageStart = 0; //开始 limit 第一个参数 private int pageEnd = 0; //结束 limit 第二个参数 private int pageIndex; //页数 private int pageSize; //行数 private T data; public OperationRequest() { } public OperationRequest(String page, String rows) { this.pageIndex = StringUtils.isEmpty(page) ? 1 : Integer.parseInt(page); this.pageSize = StringUtils.isEmpty(page) ? 10 : Integer.parseInt(rows); if (0 == this.pageIndex) { this.pageIndex = 1; } //页的偏移量,当pageIndex=1时,pageStart=0 this.pageStart = (this.pageIndex - 1) * this.pageSize; //页内偏移,每页的条数 this.pageEnd = this.pageSize; } public OperationRequest(int page, int rows) { this.pageIndex = 0 == page ? 1 : page; this.pageSize = 0 == rows ? 10 : rows; this.pageStart = (this.pageIndex - 1) * this.pageSize; this.pageEnd = this.pageSize; } public void setPage(String page, String rows) { this.pageIndex = StringUtils.isEmpty(page) ? 1 : Integer.parseInt(page); this.pageSize = StringUtils.isEmpty(page) ? 10 : Integer.parseInt(rows); if (0 == this.pageIndex) { this.pageIndex = 1; } this.pageStart = (this.pageIndex - 1) * this.pageSize; this.pageEnd = this.pageSize; } public int getPageStart() { return pageStart; } public void setPageStart(int pageStart) { this.pageStart = pageStart; } public int getPageEnd() { return pageEnd; } public void setPageEnd(int pageEnd) { this.pageEnd = pageEnd; } public T getData() { return data; } public void setData(T data) { if (data instanceof String) { String str = (String) data; if (StringUtils.isEmpty(str)){ data = null; } } this.data = data; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/common/OperationRequest.java
Java
mit
2,144
package zack.gateway.center.infrastructure.common; import java.util.List; public class OperationResult<T> { private int pageTotal; private List<T> list; public OperationResult() { } public OperationResult(int pageTotal, List<T> list) { this.pageTotal = pageTotal; this.list = list; } public int getPageTotal() { return pageTotal; } public void setPageTotal(int pageTotal) { this.pageTotal = pageTotal; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/common/OperationResult.java
Java
mit
619
package zack.gateway.center.infrastructure.common; /** * @author zack * @description 错误码 */ public enum ResponseCode { SUCCESS("0000", "成功"), UN_ERROR("0001", "未知失败"), ILLEGAL_PARAMETER("0002", "非法参数"), INDEX_DUP("0003", "主键冲突"), NO_UPDATE("0004", "SQL操作无更新"); private String code; private String info; ResponseCode(String code, String info) { this.code = code; this.info = info; } public String getCode() { return code; } public String getInfo() { return info; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/common/ResponseCode.java
Java
mit
608
package zack.gateway.center.infrastructure.common; import com.alibaba.fastjson.JSON; import java.io.Serializable; /** * @author zack * @description 统一返回对象中,Code码、Info描述 */ public class Result<T> implements Serializable { private static final long serialVersionUID = -3826891916021780628L; private String code; private String info; private T data; public Result(String code, String info, T data) { this.code = code; this.info = info; this.data = data; } public String getCode() { return code; } public String getInfo() { return info; } public T getData() { return data; } @Override public String toString() { return JSON.toJSONString(this); } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/common/Result.java
Java
mit
801
package zack.gateway.center.infrastructure.dao; import org.apache.ibatis.annotations.Mapper; import zack.gateway.center.domain.operation.model.vo.ApplicationInterfaceDataVO; import zack.gateway.center.infrastructure.common.OperationRequest; import zack.gateway.center.infrastructure.po.ApplicationInterface; import zack.gateway.center.infrastructure.po.ApplicationInterfaceMethod; import java.util.List; /** * @author zack * @description 应用接口 */ @Mapper public interface IApplicationInterfaceDao { void insert(ApplicationInterface applicationInterface); List<ApplicationInterface> queryApplicationInterfaceListBySystemId(String systemId); List<ApplicationInterface> queryApplicationInterfaceList(List<String> systemIdList); List<ApplicationInterface> queryApplicationInterfaceList(String systemId); List<ApplicationInterface> queryApplicationInterfaceListByPage(OperationRequest<ApplicationInterfaceDataVO> request); int queryApplicationInterfaceListCountByPage(OperationRequest<ApplicationInterfaceDataVO> request); }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/dao/IApplicationInterfaceDao.java
Java
mit
1,069
package zack.gateway.center.infrastructure.dao; import org.apache.ibatis.annotations.Mapper; import zack.gateway.center.domain.manage.repository.InterfaceKey; import zack.gateway.center.domain.operation.model.vo.ApplicationInterfaceMethodDataVO; import zack.gateway.center.infrastructure.common.OperationRequest; import zack.gateway.center.infrastructure.po.ApplicationInterfaceMethod; import java.util.List; /** * @author zack * @description 应用接口方法 */ @Mapper public interface IApplicationInterfaceMethodDao { void insert(ApplicationInterfaceMethod applicationInterfaceMethod); List<ApplicationInterfaceMethod> queryApplicationInterfaceMethodList(ApplicationInterfaceMethod req); List<ApplicationInterfaceMethod> queryApplicationInterfaceMethodListByKeys(List<InterfaceKey> keys); List<ApplicationInterfaceMethod> queryApplicationInterfaceMethodListByPage(OperationRequest<ApplicationInterfaceMethodDataVO> request); int queryApplicationInterfaceMethodListCountByPage(OperationRequest<ApplicationInterfaceMethodDataVO> request); }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/dao/IApplicationInterfaceMethodDao.java
Java
mit
1,084
package zack.gateway.center.infrastructure.dao; import org.apache.ibatis.annotations.Mapper; import zack.gateway.center.domain.operation.model.vo.ApplicationSystemDataVO; import zack.gateway.center.infrastructure.common.OperationRequest; import zack.gateway.center.infrastructure.po.ApplicationSystem; import java.util.List; /** * @author zack * @description 应用系统 */ @Mapper public interface IApplicationSystemDao { void insert(ApplicationSystem applicationSystem); List<ApplicationSystem> queryApplicationSystemList(List<String> applicationSystemIdList); List<ApplicationSystem> queryApplicationSystemListByPage(OperationRequest<ApplicationSystemDataVO> request); int queryApplicationSystemListCountByPage(OperationRequest<ApplicationSystemDataVO> request); ApplicationSystem queryApplicationSystemBySystemId(String systemId); }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/dao/IApplicationSystemDao.java
Java
mit
875
package zack.gateway.center.infrastructure.dao; import org.apache.ibatis.annotations.Mapper; import zack.gateway.center.domain.operation.model.vo.GatewayDistributionDataVO; import zack.gateway.center.infrastructure.common.OperationRequest; import zack.gateway.center.infrastructure.po.GatewayDistribution; import java.util.List; /** * @author zack * @description 网关分配 */ @Mapper public interface IGatewayDistributionDao { List<String> queryGatewayDistributionSystemIdList(String gatewayId); String queryGatewayDistributionBySystemId(String systemId); List<GatewayDistribution> queryGatewayDistributionListByPage(OperationRequest<GatewayDistributionDataVO> request); int queryGatewayDistributionListCountByPage(OperationRequest<GatewayDistributionDataVO> request); void insert(GatewayDistribution gatewayDistribution); }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/dao/IGatewayDistributionDao.java
Java
mit
865
package zack.gateway.center.infrastructure.dao; import org.apache.ibatis.annotations.Mapper; import zack.gateway.center.infrastructure.common.OperationRequest; import zack.gateway.center.infrastructure.po.GatewayServer; import java.util.List; /** * @author zack * @description */ @Mapper public interface IGatewayServerDao { List<GatewayServer> queryGatewayServerList(); List<GatewayServer> queryGatewayServerListByPage(OperationRequest<String> request); int queryGatewayServerListCountByPage(OperationRequest<String> request); }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/dao/IGatewayServerDao.java
Java
mit
560
package zack.gateway.center.infrastructure.dao; import org.apache.ibatis.annotations.Mapper; import zack.gateway.center.domain.operation.model.vo.GatewayServerDetaiDatalVO; import zack.gateway.center.infrastructure.common.OperationRequest; import zack.gateway.center.infrastructure.po.GatewayServerDetail; import java.util.List; /** * @author zack * @description */ @Mapper public interface IGatewayServerDetailDao { void insert(GatewayServerDetail gatewayServerDetail); GatewayServerDetail queryGatewayServerDetail(GatewayServerDetail gatewayServerDetail); boolean updateGatewayStatus(GatewayServerDetail gatewayServerDetail); List<GatewayServerDetail> queryGatewayServerDetailListByPage(OperationRequest<GatewayServerDetaiDatalVO> request); int queryGatewayServerDetailListCountByPage(OperationRequest<GatewayServerDetaiDatalVO> request); List<GatewayServerDetail> queryGatewayServerDetailList(); }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/dao/IGatewayServerDetailDao.java
Java
mit
946
package zack.gateway.center.infrastructure.po; import java.util.Date; /** * @author zack * @description 应用接口 */ public class ApplicationInterface { /** 自增ID */ private Integer id; /** 系统标识 */ private String systemId; /** 接口标识 */ private String interfaceId; /** 接口名称 */ private String interfaceName; /** 接口版本 */ private String interfaceVersion; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public String getInterfaceId() { return interfaceId; } public void setInterfaceId(String interfaceId) { this.interfaceId = interfaceId; } public String getInterfaceName() { return interfaceName; } public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } public String getInterfaceVersion() { return interfaceVersion; } public void setInterfaceVersion(String interfaceVersion) { this.interfaceVersion = interfaceVersion; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/po/ApplicationInterface.java
Java
mit
1,703
package zack.gateway.center.infrastructure.po; import java.util.Date; /** * @author zack * @description 应用接口方法 */ public class ApplicationInterfaceMethod { /** 自增ID */ private Integer id; /** 系统标识 */ private String systemId; /** 接口标识 */ private String interfaceId; /** 方法标识 */ private String methodId; /** 方法名称 */ private String methodName; /** 参数类型(RPC 限定单参数注册);new String[]{"java.lang.String"}、new String[]{"cn.bugstack.gateway.rpc.dto.XReq"} */ private String parameterType; /** 网关接口 */ private String uri; /** 接口类型;GET、POST、PUT、DELETE */ private String httpCommandType; /** 是否鉴权;true = 1是、false = 0否 */ private Integer auth; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public String getInterfaceId() { return interfaceId; } public void setInterfaceId(String interfaceId) { this.interfaceId = interfaceId; } public String getMethodId() { return methodId; } public void setMethodId(String methodId) { this.methodId = methodId; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public String getParameterType() { return parameterType; } public void setParameterType(String parameterType) { this.parameterType = parameterType; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getHttpCommandType() { return httpCommandType; } public void setHttpCommandType(String httpCommandType) { this.httpCommandType = httpCommandType; } public Integer getAuth() { return auth; } public void setAuth(Integer auth) { this.auth = auth; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/po/ApplicationInterfaceMethod.java
Java
mit
2,660
package zack.gateway.center.infrastructure.po; import java.util.Date; /** * @author zack * @description 应用系统 */ public class ApplicationSystem { /** 自增ID */ private Integer id; /** 系统标识 */ private String systemId; /** 系统名称 */ private String systemName; /** 系统类型;RPC、HTTP*/ private String systemType; /** 注册中心;zookeeper://127.0.0.1:2181*/ private String systemRegistry; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public String getSystemName() { return systemName; } public void setSystemName(String systemName) { this.systemName = systemName; } public String getSystemType() { return systemType; } public void setSystemType(String systemType) { this.systemType = systemType; } public String getSystemRegistry() { return systemRegistry; } public void setSystemRegistry(String systemRegistry) { this.systemRegistry = systemRegistry; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/po/ApplicationSystem.java
Java
mit
1,698
package zack.gateway.center.infrastructure.po; import java.util.Date; /** * @author zack * @description 网关分配 */ public class GatewayDistribution { /** 自增主键 */ private Integer id; /** 分组标识 */ private String groupId; /** 网关标识 */ private String gatewayId; /** 系统标识 */ private String systemId; /** 系统名称 */ private String systemName; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getGatewayId() { return gatewayId; } public void setGatewayId(String gatewayId) { this.gatewayId = gatewayId; } public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public String getSystemName() { return systemName; } public void setSystemName(String systemName) { this.systemName = systemName; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/po/GatewayDistribution.java
Java
mit
1,608
package zack.gateway.center.infrastructure.po; /** * @author zack * @description 网关服务 */ public class GatewayServer { /** 自增主键 */ private Integer id; /** 分组标识 */ private String groupId; /** 分组名称 */ private String groupName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/po/GatewayServer.java
Java
mit
720
package zack.gateway.center.infrastructure.po; import java.util.Date; /** * @author zack * @description 网关服务明细 */ public class GatewayServerDetail { /** 自增ID */ private Integer id; /** 分组标识 */ private String groupId; /** 网关标识 */ private String gatewayId; /** 网关名称 */ private String gatewayName; /** 网关地址 */ private String gatewayAddress; /** 服务状态 */ private Integer status; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getGatewayId() { return gatewayId; } public void setGatewayId(String gatewayId) { this.gatewayId = gatewayId; } public String getGatewayName() { return gatewayName; } public void setGatewayName(String gatewayName) { this.gatewayName = gatewayName; } public String getGatewayAddress() { return gatewayAddress; } public void setGatewayAddress(String gatewayAddress) { this.gatewayAddress = gatewayAddress; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/po/GatewayServerDetail.java
Java
mit
1,855
package zack.gateway.center.infrastructure.repository; import org.springframework.stereotype.Component; import zack.gateway.center.domain.manage.model.vo.GatewayServerDetailVO; import zack.gateway.center.domain.manage.model.vo.GatewayServerVO; import zack.gateway.center.domain.manage.repository.IConfigManageRepository; import zack.gateway.center.domain.manage.model.vo.ApplicationInterfaceMethodVO; import zack.gateway.center.domain.manage.model.vo.ApplicationInterfaceVO; import zack.gateway.center.domain.manage.model.vo.ApplicationSystemVO; import zack.gateway.center.domain.manage.repository.InterfaceKey; import zack.gateway.center.infrastructure.dao.*; import zack.gateway.center.infrastructure.po.*; import javax.annotation.Resource; import java.sql.Array; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author zack * @description 网关配置仓储服务 */ @Component public class ConfigManageRepository implements IConfigManageRepository { @Resource private IGatewayServerDao gatewayServerDao; @Resource private IGatewayServerDetailDao gatewayServerDetailDao; @Resource IApplicationSystemDao applicationSystemDao; @Resource IApplicationInterfaceDao applicationInterfaceDao; @Resource IApplicationInterfaceMethodDao applicationInterfaceMethodDao; @Resource IGatewayDistributionDao gatewayDistributionDao; @Override public List<GatewayServerVO> queryGatewayServerList() { List<GatewayServer> gatewayServers = gatewayServerDao.queryGatewayServerList(); List<GatewayServerVO> gatewayServerVOList = new ArrayList<>(gatewayServers.size()); for (GatewayServer gatewayServer : gatewayServers) { // 可以按照 IDEA 插件 vo2dto 方便转换 GatewayServerVO gatewayServerVO = new GatewayServerVO(); gatewayServerVO.setGroupId(gatewayServer.getGroupId()); gatewayServerVO.setGroupName(gatewayServer.getGroupName()); gatewayServerVOList.add(gatewayServerVO); } return gatewayServerVOList; } @Override public boolean registerGatewayServerNode(String groupId, String gatewayId, String gatewayName, String gatewayAddress, Integer status) { GatewayServerDetail gatewayServerDetail = new GatewayServerDetail(); gatewayServerDetail.setGroupId(groupId); gatewayServerDetail.setGatewayId(gatewayId); gatewayServerDetail.setGatewayName(gatewayName); gatewayServerDetail.setGatewayAddress(gatewayAddress); gatewayServerDetail.setStatus(status); gatewayServerDetailDao.insert(gatewayServerDetail); return true; } @Override public GatewayServerDetailVO queryGatewayServerDetail(String gatewayId, String gatewayAddress) { GatewayServerDetail req = new GatewayServerDetail(); req.setGatewayId(gatewayId); req.setGatewayAddress(gatewayAddress); GatewayServerDetail gatewayServerDetail = gatewayServerDetailDao.queryGatewayServerDetail(req); if (null == gatewayServerDetail) return null; // 可以按照 IDEA 插件 vo2dto 方便转换 GatewayServerDetailVO gatewayServerDetailVO = new GatewayServerDetailVO(); gatewayServerDetailVO.setGatewayId(gatewayServerDetail.getGatewayId()); gatewayServerDetailVO.setGatewayName(gatewayServerDetail.getGatewayName()); gatewayServerDetailVO.setGatewayAddress(gatewayServerDetail.getGatewayAddress()); gatewayServerDetailVO.setStatus(gatewayServerDetail.getStatus()); return gatewayServerDetailVO; } @Override public boolean updateGatewayStatus(String gatewayId, String gatewayAddress, Integer available) { GatewayServerDetail gatewayServerDetail = new GatewayServerDetail(); gatewayServerDetail.setGatewayId(gatewayId); gatewayServerDetail.setGatewayAddress(gatewayAddress); gatewayServerDetail.setStatus(available); return gatewayServerDetailDao.updateGatewayStatus(gatewayServerDetail); } /** * 根据网关id来查询与该网关关联的rpc应用id * @param gatewayId * @return */ @Override public List<String> queryGatewayDistributionSystemIdList(String gatewayId) { return gatewayDistributionDao.queryGatewayDistributionSystemIdList(gatewayId); } /** * 根据systemId来查询rpc应用 * @param systemIdList * @return */ @Override public List<ApplicationSystemVO> queryApplicationSystemList(List<String> systemIdList) { List<ApplicationSystemVO> applicationSystemVOS = new ArrayList<>(); List<ApplicationSystem> applicationSystems = applicationSystemDao.queryApplicationSystemList(systemIdList); for(ApplicationSystem applicationSystem : applicationSystems ) { ApplicationSystemVO applicationSystemVO = new ApplicationSystemVO(); applicationSystemVO.setSystemId(applicationSystem.getSystemId()); applicationSystemVO.setSystemName(applicationSystem.getSystemName()); applicationSystemVO.setSystemType(applicationSystem.getSystemType()); applicationSystemVO.setSystemRegistry(applicationSystem.getSystemRegistry()); applicationSystemVOS.add(applicationSystemVO); } return applicationSystemVOS; } @Override public List<ApplicationInterfaceVO> queryApplicationInterfaceList(String systemId) { return Collections.emptyList(); } @Override public List<ApplicationInterfaceVO> queryApplicationInterfaceList(List<String> interfaceIdList) { List<ApplicationInterfaceVO> applicationInterfaceVOS = new ArrayList<>(); List<ApplicationInterface> applicationInterfaces = applicationInterfaceDao.queryApplicationInterfaceList(interfaceIdList); for(ApplicationInterface applicationInterface : applicationInterfaces ) { ApplicationInterfaceVO applicationInterfaceVO = new ApplicationInterfaceVO(); applicationInterfaceVO.setSystemId(applicationInterface.getSystemId()); applicationInterfaceVO.setInterfaceId(applicationInterface.getInterfaceId()); applicationInterfaceVO.setInterfaceName(applicationInterface.getInterfaceName()); applicationInterfaceVO.setInterfaceVersion(applicationInterface.getInterfaceVersion()); applicationInterfaceVOS.add(applicationInterfaceVO); } return applicationInterfaceVOS; } @Override public List<ApplicationInterfaceMethodVO> queryApplicationInterfaceMethodList(String systemId, String interfaceId) { return Collections.emptyList(); } @Override public List<ApplicationInterfaceMethodVO> queryApplicationInterfaceMethodListByKeys(List<InterfaceKey> keys) { List<ApplicationInterfaceMethodVO> interfaceMethodVOS = new ArrayList<>(); List<ApplicationInterfaceMethod> interfaceMethods = applicationInterfaceMethodDao.queryApplicationInterfaceMethodListByKeys(keys); for(ApplicationInterfaceMethod applicationInterfaceMethod : interfaceMethods ) { ApplicationInterfaceMethodVO applicationInterfaceMethodVO = new ApplicationInterfaceMethodVO(); applicationInterfaceMethodVO.setSystemId(applicationInterfaceMethod.getSystemId()); applicationInterfaceMethodVO.setInterfaceId(applicationInterfaceMethod.getInterfaceId()); applicationInterfaceMethodVO.setMethodId(applicationInterfaceMethod.getMethodId()); applicationInterfaceMethodVO.setMethodName(applicationInterfaceMethod.getMethodName()); applicationInterfaceMethodVO.setParameterType(applicationInterfaceMethod.getParameterType()); applicationInterfaceMethodVO.setUri(applicationInterfaceMethod.getUri()); applicationInterfaceMethodVO.setHttpCommandType(applicationInterfaceMethod.getHttpCommandType()); applicationInterfaceMethodVO.setAuth(applicationInterfaceMethod.getAuth()); interfaceMethodVOS.add(applicationInterfaceMethodVO); } return interfaceMethodVOS; } @Override public String queryGatewayDistributionBySystemId(String systemId) { return gatewayDistributionDao.queryGatewayDistributionBySystemId(systemId); } @Override public List<GatewayServerDetailVO> queryGatewayServerDetailList() { List<GatewayServerDetail> gatewayServerVOList = gatewayServerDetailDao.queryGatewayServerDetailList(); List<GatewayServerDetailVO> gatewayServerDetailVOS = new ArrayList<>(); for(GatewayServerDetail gatewayServerDetail : gatewayServerVOList ) { GatewayServerDetailVO gatewayServerDetailVO = new GatewayServerDetailVO(); gatewayServerDetailVO.setGatewayId(gatewayServerDetail.getGatewayId()); gatewayServerDetailVO.setGatewayName(gatewayServerDetail.getGatewayName()); gatewayServerDetailVO.setGatewayAddress(gatewayServerDetail.getGatewayAddress()); gatewayServerDetailVO.setStatus(gatewayServerDetail.getStatus()); gatewayServerDetailVO.setId(gatewayServerDetail.getId()); gatewayServerDetailVO.setGroupId(gatewayServerDetail.getGroupId()); gatewayServerDetailVO.setCreateTime(gatewayServerDetail.getCreateTime()); gatewayServerDetailVO.setUpdateTime(gatewayServerDetail.getUpdateTime()); gatewayServerDetailVOS.add(gatewayServerDetailVO); } return gatewayServerDetailVOS; } @Override public ApplicationSystemVO queryApplicationSystemBySystemId(String systemId) { ApplicationSystem system = applicationSystemDao.queryApplicationSystemBySystemId(systemId); if(system == null) { return null; } ApplicationSystemVO applicationSystemVO = new ApplicationSystemVO(); applicationSystemVO.setSystemId(system.getSystemId()); applicationSystemVO.setSystemName(system.getSystemName()); applicationSystemVO.setSystemType(system.getSystemType()); applicationSystemVO.setSystemRegistry(system.getSystemRegistry()); return applicationSystemVO; } @Override public void distributionGatewayServerNode(String groupId, String gatewayId, String systemId, String systemName) { GatewayDistribution gatewayDistribution = new GatewayDistribution(); gatewayDistribution.setGroupId(groupId); gatewayDistribution.setGatewayId(gatewayId); gatewayDistribution.setSystemId(systemId); gatewayDistribution.setSystemName(systemName); gatewayDistributionDao.insert(gatewayDistribution); } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/repository/ConfigManageRepository.java
Java
mit
10,670
package zack.gateway.center.infrastructure.repository; import zack.gateway.center.domain.operation.model.vo.*; import zack.gateway.center.domain.operation.repository.IDataOperationManageRepository; import zack.gateway.center.infrastructure.common.OperationRequest; import zack.gateway.center.infrastructure.dao.*; import zack.gateway.center.infrastructure.po.*; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; /** * @author zack * @description */ @Component public class DataOperationManageRepository implements IDataOperationManageRepository { @Resource private IGatewayServerDao gatewayServerDao; @Resource private IGatewayServerDetailDao gatewayServerDetailDao; @Resource private IGatewayDistributionDao gatewayDistributionDao; @Resource private IApplicationSystemDao applicationSystemDao; @Resource private IApplicationInterfaceDao applicationInterfaceDao; @Resource private IApplicationInterfaceMethodDao applicationInterfaceMethodDao; @Override public List<GatewayServerDataVO> queryGatewayServerListByPage(OperationRequest<String> request) { List<GatewayServer> gatewayServers = gatewayServerDao.queryGatewayServerListByPage(request); List<GatewayServerDataVO> gatewayServerVOList = new ArrayList<>(gatewayServers.size()); for (GatewayServer gatewayServer : gatewayServers) { // 可以按照 IDEA 插件 vo2dto 方便转换 GatewayServerDataVO gatewayServerVO = new GatewayServerDataVO(); gatewayServerVO.setId(gatewayServer.getId()); gatewayServerVO.setGroupId(gatewayServer.getGroupId()); gatewayServerVO.setGroupName(gatewayServer.getGroupName()); gatewayServerVOList.add(gatewayServerVO); } return gatewayServerVOList; } @Override public int queryGatewayServerListCountByPage(OperationRequest<String> request) { return gatewayServerDao.queryGatewayServerListCountByPage(request); } @Override public List<ApplicationSystemDataVO> queryApplicationSystemListByPage(OperationRequest<ApplicationSystemDataVO> request) { List<ApplicationSystem> applicationSystems = applicationSystemDao.queryApplicationSystemListByPage(request); List<ApplicationSystemDataVO> applicationSystemDataVOList = new ArrayList<>(applicationSystems.size()); for (ApplicationSystem applicationSystem : applicationSystems) { ApplicationSystemDataVO applicationSystemDataVO = new ApplicationSystemDataVO(); applicationSystemDataVO.setSystemId(applicationSystem.getSystemId()); applicationSystemDataVO.setSystemName(applicationSystem.getSystemName()); applicationSystemDataVO.setSystemType(applicationSystem.getSystemType()); applicationSystemDataVO.setSystemRegistry(applicationSystem.getSystemRegistry()); applicationSystemDataVOList.add(applicationSystemDataVO); } return applicationSystemDataVOList; } @Override public int queryApplicationSystemListCountByPage(OperationRequest<ApplicationSystemDataVO> request) { return applicationSystemDao.queryApplicationSystemListCountByPage(request); } @Override public List<ApplicationInterfaceDataVO> queryApplicationInterfaceListByPage(OperationRequest<ApplicationInterfaceDataVO> request) { List<ApplicationInterface> applicationInterfaces = applicationInterfaceDao.queryApplicationInterfaceListByPage(request); List<ApplicationInterfaceDataVO> applicationInterfaceDataVOList = new ArrayList<>(applicationInterfaces.size()); for (ApplicationInterface applicationInterface : applicationInterfaces) { ApplicationInterfaceDataVO applicationInterfaceDataVO = new ApplicationInterfaceDataVO(); applicationInterfaceDataVO.setSystemId(applicationInterface.getSystemId()); applicationInterfaceDataVO.setInterfaceId(applicationInterface.getInterfaceId()); applicationInterfaceDataVO.setInterfaceName(applicationInterface.getInterfaceName()); applicationInterfaceDataVO.setInterfaceVersion(applicationInterface.getInterfaceVersion()); applicationInterfaceDataVOList.add(applicationInterfaceDataVO); } return applicationInterfaceDataVOList; } @Override public int queryApplicationInterfaceListCountByPage(OperationRequest<ApplicationInterfaceDataVO> request) { return applicationInterfaceDao.queryApplicationInterfaceListCountByPage(request); } @Override public List<ApplicationInterfaceMethodDataVO> queryApplicationInterfaceMethodListByPage(OperationRequest<ApplicationInterfaceMethodDataVO> request) { List<ApplicationInterfaceMethod> applicationInterfaceMethods = applicationInterfaceMethodDao.queryApplicationInterfaceMethodListByPage(request); List<ApplicationInterfaceMethodDataVO> applicationInterfaceMethodDataVOList = new ArrayList<>(applicationInterfaceMethods.size()); for (ApplicationInterfaceMethod applicationInterfaceMethod : applicationInterfaceMethods) { ApplicationInterfaceMethodDataVO applicationInterfaceMethodDataVO = new ApplicationInterfaceMethodDataVO(); applicationInterfaceMethodDataVO.setSystemId(applicationInterfaceMethod.getSystemId()); applicationInterfaceMethodDataVO.setInterfaceId(applicationInterfaceMethod.getInterfaceId()); applicationInterfaceMethodDataVO.setMethodId(applicationInterfaceMethod.getMethodId()); applicationInterfaceMethodDataVO.setMethodName(applicationInterfaceMethod.getMethodName()); applicationInterfaceMethodDataVO.setParameterType(applicationInterfaceMethod.getParameterType()); applicationInterfaceMethodDataVO.setUri(applicationInterfaceMethod.getUri()); applicationInterfaceMethodDataVO.setHttpCommandType(applicationInterfaceMethod.getHttpCommandType()); applicationInterfaceMethodDataVO.setAuth(applicationInterfaceMethod.getAuth()); applicationInterfaceMethodDataVOList.add(applicationInterfaceMethodDataVO); } return applicationInterfaceMethodDataVOList; } @Override public int queryApplicationInterfaceMethodListCountByPage(OperationRequest<ApplicationInterfaceMethodDataVO> request) { return applicationInterfaceMethodDao.queryApplicationInterfaceMethodListCountByPage(request); } @Override public List<GatewayServerDetaiDatalVO> queryGatewayServerDetailListByPage(OperationRequest<GatewayServerDetaiDatalVO> request) { List<GatewayServerDetail> applicationInterfaceMethods = gatewayServerDetailDao.queryGatewayServerDetailListByPage(request); List<GatewayServerDetaiDatalVO> gatewayServerDetailDataVOList = new ArrayList<>(applicationInterfaceMethods.size()); for (GatewayServerDetail gatewayServerDetail : applicationInterfaceMethods) { GatewayServerDetaiDatalVO gatewayServerDetaiDatalVO = new GatewayServerDetaiDatalVO(); gatewayServerDetaiDatalVO.setId(gatewayServerDetail.getId()); gatewayServerDetaiDatalVO.setGroupId(gatewayServerDetail.getGroupId()); gatewayServerDetaiDatalVO.setGatewayId(gatewayServerDetail.getGatewayId()); gatewayServerDetaiDatalVO.setGatewayName(gatewayServerDetail.getGatewayName()); gatewayServerDetaiDatalVO.setGatewayAddress(gatewayServerDetail.getGatewayAddress()); gatewayServerDetaiDatalVO.setStatus(gatewayServerDetail.getStatus()); gatewayServerDetaiDatalVO.setCreateTime(gatewayServerDetail.getCreateTime()); gatewayServerDetaiDatalVO.setUpdateTime(gatewayServerDetail.getUpdateTime()); gatewayServerDetailDataVOList.add(gatewayServerDetaiDatalVO); } return gatewayServerDetailDataVOList; } @Override public int queryGatewayServerDetailListCountByPage(OperationRequest<GatewayServerDetaiDatalVO> request) { return gatewayServerDetailDao.queryGatewayServerDetailListCountByPage(request); } @Override public List<GatewayDistributionDataVO> queryGatewayDistributionListByPage(OperationRequest<GatewayDistributionDataVO> request) { List<GatewayDistribution> gatewayDistributions = gatewayDistributionDao.queryGatewayDistributionListByPage(request); List<GatewayDistributionDataVO> gatewayServerDetailDataVOList = new ArrayList<>(gatewayDistributions.size()); for (GatewayDistribution gatewayDistribution : gatewayDistributions) { GatewayDistributionDataVO gatewayDistributionDataVO = new GatewayDistributionDataVO(); gatewayDistributionDataVO.setId(gatewayDistribution.getId()); gatewayDistributionDataVO.setGroupId(gatewayDistribution.getGroupId()); gatewayDistributionDataVO.setGatewayId(gatewayDistribution.getGatewayId()); gatewayDistributionDataVO.setSystemId(gatewayDistribution.getSystemId()); gatewayDistributionDataVO.setSystemName(gatewayDistribution.getSystemName()); gatewayDistributionDataVO.setCreateTime(gatewayDistribution.getCreateTime()); gatewayDistributionDataVO.setUpdateTime(gatewayDistribution.getUpdateTime()); gatewayServerDetailDataVOList.add(gatewayDistributionDataVO); } return gatewayServerDetailDataVOList; } @Override public int queryGatewayDistributionListCountByPage(OperationRequest<GatewayDistributionDataVO> request) { return gatewayDistributionDao.queryGatewayDistributionListCountByPage(request); } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/repository/DataOperationManageRepository.java
Java
mit
9,714
package zack.gateway.center.infrastructure.repository; import org.springframework.stereotype.Component; import zack.gateway.center.domain.register.model.vo.ApplicationInterfaceMethodVO; import zack.gateway.center.domain.register.model.vo.ApplicationInterfaceVO; import zack.gateway.center.domain.register.model.vo.ApplicationSystemVO; import zack.gateway.center.domain.register.repository.IRegisterManageRepository; import zack.gateway.center.infrastructure.dao.IApplicationInterfaceDao; import zack.gateway.center.infrastructure.dao.IApplicationInterfaceMethodDao; import zack.gateway.center.infrastructure.dao.IApplicationSystemDao; import zack.gateway.center.infrastructure.po.ApplicationInterface; import zack.gateway.center.infrastructure.po.ApplicationInterfaceMethod; import zack.gateway.center.infrastructure.po.ApplicationSystem; import javax.annotation.Resource; /** * @author zack * @description 接口注册仓储服务 */ @Component public class RegisterManageRepository implements IRegisterManageRepository { @Resource private IApplicationSystemDao applicationSystemDao; @Resource private IApplicationInterfaceDao applicationInterfaceDao; @Resource private IApplicationInterfaceMethodDao applicationInterfaceMethodDao; @Override public void registerApplication(ApplicationSystemVO applicationSystemVO) { ApplicationSystem applicationSystem = new ApplicationSystem(); applicationSystem.setSystemId(applicationSystemVO.getSystemId()); applicationSystem.setSystemName(applicationSystemVO.getSystemName()); applicationSystem.setSystemType(applicationSystemVO.getSystemType()); applicationSystem.setSystemRegistry(applicationSystemVO.getSystemRegistry()); applicationSystemDao.insert(applicationSystem); } @Override public void registerApplicationInterface(ApplicationInterfaceVO applicationInterfaceVO) { ApplicationInterface applicationInterface = new ApplicationInterface(); applicationInterface.setSystemId(applicationInterfaceVO.getSystemId()); applicationInterface.setInterfaceId(applicationInterfaceVO.getInterfaceId()); applicationInterface.setInterfaceName(applicationInterfaceVO.getInterfaceName()); applicationInterface.setInterfaceVersion(applicationInterfaceVO.getInterfaceVersion()); applicationInterfaceDao.insert(applicationInterface); } @Override public void registerApplicationInterfaceMethod(ApplicationInterfaceMethodVO applicationInterfaceMethodVO) { ApplicationInterfaceMethod applicationInterfaceMethod = new ApplicationInterfaceMethod(); applicationInterfaceMethod.setSystemId(applicationInterfaceMethodVO.getSystemId()); applicationInterfaceMethod.setInterfaceId(applicationInterfaceMethodVO.getInterfaceId()); applicationInterfaceMethod.setMethodId(applicationInterfaceMethodVO.getMethodId()); applicationInterfaceMethod.setMethodName(applicationInterfaceMethodVO.getMethodName()); applicationInterfaceMethod.setParameterType(applicationInterfaceMethodVO.getParameterType()); applicationInterfaceMethod.setUri(applicationInterfaceMethodVO.getUri()); applicationInterfaceMethod.setHttpCommandType(applicationInterfaceMethodVO.getHttpCommandType()); applicationInterfaceMethod.setAuth(applicationInterfaceMethodVO.getAuth()); applicationInterfaceMethodDao.insert(applicationInterfaceMethod); } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/infrastructure/repository/RegisterManageRepository.java
Java
mit
3,480
package zack.gateway.center.interfaces; import zack.gateway.center.application.IDataOperationManageService; import zack.gateway.center.domain.operation.model.vo.*; import zack.gateway.center.infrastructure.common.OperationRequest; import zack.gateway.center.infrastructure.common.OperationResult; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; /** * @author zack * @description 网关数据操作管理 */ @CrossOrigin // @CrossOrigin("https://bugstack.cn") @RestController @RequestMapping("/wg/admin/data") public class DataOperationManage { private Logger logger = LoggerFactory.getLogger(DataOperationManage.class); @Resource private IDataOperationManageService dataOperationManageService; @GetMapping(value = "queryGatewayServer", produces = "application/json;charset=utf-8") public OperationResult<GatewayServerDataVO> queryGatewayServer(@RequestParam String groupId, @RequestParam String page, @RequestParam String limit) { try { logger.info("查询网关服务数据开始 groupId:{} page:{} limit:{}", groupId, page, limit); OperationRequest<String> req = new OperationRequest<>(page, limit); req.setData(groupId); OperationResult<GatewayServerDataVO> operationResult = dataOperationManageService.queryGatewayServer(req); logger.info("查询网关服务数据完成 operationResult:{}", JSON.toJSONString(operationResult)); return operationResult; } catch (Exception e) { logger.error("查询网关服务数据异常 groupId:{}", groupId, e); return new OperationResult<>(0, null); } } @GetMapping(value = "queryGatewayServerDetail", produces = "application/json;charset=utf-8") public OperationResult<GatewayServerDetaiDatalVO> queryGatewayServerDetail(@RequestParam String groupId, @RequestParam String gatewayId, @RequestParam String page, @RequestParam String limit) { try { logger.info("查询网关服务详情数据开始 groupId:{} gatewayId:{} page:{} limit:{}", groupId, gatewayId, page, limit); OperationRequest<GatewayServerDetaiDatalVO> req = new OperationRequest<>(page, limit); req.setData(new GatewayServerDetaiDatalVO(groupId, gatewayId)); OperationResult<GatewayServerDetaiDatalVO> operationResult = dataOperationManageService.queryGatewayServerDetail(req); logger.info("查询网关服务详情数据完成 operationResult:{}", JSON.toJSONString(operationResult)); return operationResult; } catch (Exception e) { logger.error("查询网关服务详情数据异常 groupId:{}", groupId, e); return new OperationResult<>(0, null); } } @GetMapping(value = "queryGatewayDistribution", produces = "application/json;charset=utf-8") public OperationResult<GatewayDistributionDataVO> queryGatewayDistribution(@RequestParam String groupId, @RequestParam String gatewayId, @RequestParam String page, @RequestParam String limit) { try { logger.info("查询网关分配数据开始 groupId:{} gatewayId:{} page:{} limit:{}", groupId, gatewayId, page, limit); OperationRequest<GatewayDistributionDataVO> req = new OperationRequest<>(page, limit); req.setData(new GatewayDistributionDataVO(groupId, gatewayId)); OperationResult<GatewayDistributionDataVO> operationResult = dataOperationManageService.queryGatewayDistribution(req); logger.info("查询网关分配数据完成 operationResult:{}", JSON.toJSONString(operationResult)); return operationResult; } catch (Exception e) { logger.error("查询网关分配数据异常 groupId:{}", groupId, e); return new OperationResult<>(0, null); } } @GetMapping(value = "queryApplicationSystem", produces = "application/json;charset=utf-8") public OperationResult<ApplicationSystemDataVO> queryApplicationSystem(@RequestParam String systemId, @RequestParam String systemName, @RequestParam String page, @RequestParam String limit) { try { logger.info("查询应用系统信息开始 systemId:{} systemName:{} page:{} limit:{}", systemId, systemName, page, limit); OperationRequest<ApplicationSystemDataVO> req = new OperationRequest<>(page, limit); req.setData(new ApplicationSystemDataVO(systemId, systemName)); OperationResult<ApplicationSystemDataVO> operationResult = dataOperationManageService.queryApplicationSystem(req); logger.info("查询应用系统信息完成 operationResult:{}", JSON.toJSONString(operationResult)); return operationResult; } catch (Exception e) { logger.error("查询应用系统信息异常 systemId:{} systemName:{}", systemId, systemId, e); return new OperationResult<>(0, null); } } @GetMapping(value = "queryApplicationInterface", produces = "application/json;charset=utf-8") public OperationResult<ApplicationInterfaceDataVO> queryApplicationInterface(@RequestParam String systemId, @RequestParam String interfaceId, @RequestParam String page, @RequestParam String limit) { try { logger.info("查询应用接口信息开始 systemId:{} interfaceId:{} page:{} limit:{}", systemId, interfaceId, page, limit); OperationRequest<ApplicationInterfaceDataVO> req = new OperationRequest<>(page, limit); req.setData(new ApplicationInterfaceDataVO(systemId, interfaceId)); OperationResult<ApplicationInterfaceDataVO> operationResult = dataOperationManageService.queryApplicationInterface(req); logger.info("查询应用接口信息完成 operationResult:{}", JSON.toJSONString(operationResult)); return operationResult; } catch (Exception e) { logger.error("查询应用接口信息异常 systemId:{} interfaceId:{}", systemId, interfaceId, e); return new OperationResult<>(0, null); } } @GetMapping(value = "queryApplicationInterfaceMethodList", produces = "application/json;charset=utf-8") public OperationResult<ApplicationInterfaceMethodDataVO> queryApplicationInterfaceMethodList(@RequestParam String systemId, @RequestParam String interfaceId, @RequestParam String page, @RequestParam String limit) { try { logger.info("查询应用接口方法信息开始 systemId:{} interfaceId:{} page:{} limit:{}", systemId, interfaceId, page, limit); OperationRequest<ApplicationInterfaceMethodDataVO> req = new OperationRequest<>(page, limit); req.setData(new ApplicationInterfaceMethodDataVO(systemId, interfaceId)); OperationResult<ApplicationInterfaceMethodDataVO> operationResult = dataOperationManageService.queryApplicationInterfaceMethod(req); logger.info("查询应用接口方法信息完成 operationResult:{}", JSON.toJSONString(operationResult)); return operationResult; } catch (Exception e) { logger.error("查询应用接口方法信息异常 systemId:{} interfaceId:{}", systemId, interfaceId, e); return new OperationResult<>(0, null); } } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/interfaces/DataOperationManage.java
Java
mit
8,834
package zack.gateway.center.interfaces; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DuplicateKeyException; import org.springframework.web.bind.annotation.*; import zack.gateway.center.application.IConfigManageService; import zack.gateway.center.application.ILoadBalancingService; import zack.gateway.center.application.IMessageService; import zack.gateway.center.domain.docker.model.aggregates.NginxConfig; import zack.gateway.center.domain.docker.model.vo.LocationVO; import zack.gateway.center.domain.docker.model.vo.UpstreamVO; import zack.gateway.center.domain.manage.model.aggregates.ApplicationSystemRichInfo; import zack.gateway.center.domain.manage.model.vo.GatewayServerDetailVO; import zack.gateway.center.domain.manage.model.vo.GatewayServerVO; import zack.gateway.center.domain.message.service.config.PublisherConfig; import zack.gateway.center.infrastructure.common.ResponseCode; import zack.gateway.center.infrastructure.common.Result; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * @author zack * @description 网关配置管理;服务分组、网关注册、服务关联 * 1. 查询网关服务配置项信息:/wg/admin/config/queryServerConfig * 2. 注册网关服务节点:/wg/admin/config/registerGateway */ @RestController @RequestMapping("/wg/admin/config") public class GatewayConfigManage { private Logger logger = LoggerFactory.getLogger(GatewayConfigManage.class); @Resource private IMessageService messageService; @Resource ILoadBalancingService loadBalancingService; @Resource private IConfigManageService configManageService; @GetMapping(value = "queryServerConfig", produces = "application/json;charset=utf-8") public Result<List<GatewayServerVO>> queryServerConfig() { try { logger.info("查询网关服务配置项信息"); List<GatewayServerVO> gatewayServerVOList = configManageService.queryGatewayServerList(); return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), gatewayServerVOList); } catch (Exception e) { logger.error("查询网关服务配置项信息异常", e); return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), null); } } /** * 注册网关服务节点 * * @param groupId 分组标识 * @param gatewayId 网关标识 * @param gatewayName 网关名称 * @param gatewayAddress 网关地址 * @return 注册状态 */ @PostMapping(value = "registerGateway") public Result<Boolean> registerGatewayServerNode(@RequestParam String groupId, @RequestParam String gatewayId, @RequestParam String gatewayName, @RequestParam String gatewayAddress) { try { logger.info("注册网关服务节点 gatewayId:{} gatewayName:{} gatewayAddress:{}", gatewayId, gatewayName, gatewayAddress); boolean done = configManageService.registerGatewayServerNode(groupId, gatewayId, gatewayName, gatewayAddress); if(done) { logger.info("注册算力成功"); }else{ logger.info("算力注册失败"); } //查询最新网关算力配置 List<GatewayServerDetailVO> gatewayServerDetailVOList = configManageService.queryGatewayServerDetailList(); //将同一个组的网关放在一起 Map<String, List<GatewayServerDetailVO>> details = gatewayServerDetailVOList.stream().collect(Collectors.groupingBy(GatewayServerDetailVO::getGroupId)); Set<String> groupIds = details.keySet(); //locationVO是分组,路由和转发的配置 List<LocationVO> locationVOS = new ArrayList<>(); for(String name :groupIds){ LocationVO locationVO = new LocationVO("/" + name + "/", "http://" + name + ";"); locationVOS.add(locationVO); } List<UpstreamVO> upstreamVOS = new ArrayList<>(); for(String name :groupIds){ List<String> gatewayAddressList = details.get(name).stream().map(GatewayServerDetailVO::getGatewayAddress).collect(Collectors.toList()); UpstreamVO leastConn = new UpstreamVO(name, "least_conn;", gatewayAddressList); upstreamVOS.add(leastConn); } loadBalancingService.updateNginxConfig(new NginxConfig(upstreamVOS, locationVOS)); return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), done); } catch (Exception e) { logger.error("注册网关服务节点异常", e); return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), false); } } @PostMapping(value = "queryApplicationSystemRichInfo", produces = "application/json;charset=utf-8") public Result<ApplicationSystemRichInfo> queryApplicationSystemRichInfo(@RequestParam String gatewayId,@RequestParam String systemId) { try { logger.info("查询分配到网关下的待注册系统信息(系统、接口、方法) gatewayId:{}", gatewayId); ApplicationSystemRichInfo applicationSystemRichInfo = configManageService.queryApplicationSystemRichInfo(gatewayId,systemId); if(applicationSystemRichInfo == null) { return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), null); } return new Result<ApplicationSystemRichInfo>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), applicationSystemRichInfo); } catch (Exception e) { logger.error("查询分配到网关下的待注册系统信息(系统、接口、方法)异常 gatewayId:{}", gatewayId, e); return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), null); } } @PostMapping(value = "queryRedisConfig", produces = "application/json;charset=utf-8") public Result<Map<String, String>> queryRedisConfig() { try { logger.info("查询配置中心Redis配置信息"); Map<String, String> redisConfig = messageService.queryRedisConfig(); return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), redisConfig); } catch (Exception e) { logger.error("查询配置中心Redis配置信息失败", e); return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), null); } } public Result<Boolean> distributionGatewayServerNode(@RequestParam String groupId,@RequestParam String gatewayId,@RequestParam String systemId) { try { configManageService.distributionGatewayServerNode(groupId, gatewayId, systemId); return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), true); } catch (DuplicateKeyException e) { logger.warn("查询应用服务配置项信息失败,唯一索引冲突。groupId:{} gatewayId:{} systemId:{}", groupId, gatewayId, systemId, e); return new Result<>(ResponseCode.INDEX_DUP.getCode(), e.getMessage(), true); } catch (Exception e) { logger.error("网关算力与系统挂载配置。groupId:{} gatewayId:{} systemId:{}", groupId, gatewayId, systemId, e); return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), false); } } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/interfaces/GatewayConfigManage.java
Java
mit
7,765
package zack.gateway.center.interfaces; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import zack.gateway.center.application.ILoadBalancingService; import zack.gateway.center.domain.docker.model.aggregates.NginxConfig; import zack.gateway.center.domain.docker.model.vo.LocationVO; import zack.gateway.center.domain.docker.model.vo.UpstreamVO; import javax.annotation.Resource; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.mysql.cj.conf.PropertyKey.logger; /** * @author A1793 */ @RestController @RequestMapping("/wg/admin/load") public class LoadBalancingMange { private Logger logger = LoggerFactory.getLogger(GatewayConfigManage.class); @Resource ILoadBalancingService loadBalancingService; public void copy() throws IOException { ProcessBuilder pb = new ProcessBuilder("docker", "cp", "/nginx.conf", "host:/mnt/c/javaData/git_test/my-api-gateway-center/docs/data/nginx/nginx.conf"); pb.start(); } @GetMapping(value = "updateNginxConfig", produces = "application/json;charset=utf-8") public void updateNginxConfig() { List<UpstreamVO> upstreamList = new ArrayList<>(); upstreamList.add(new UpstreamVO("api01", "least_conn;", Arrays.asList("10.114.109.46:9001;", "10.114.109.46:9002;"))); upstreamList.add(new UpstreamVO("api02", "least_conn;", Arrays.asList("10.114.109.46:9003;"))); List<LocationVO> locationList = new ArrayList<>(); locationList.add(new LocationVO("/api01/", "http://api01;")); locationList.add(new LocationVO("/api02/", "http://api02;")); NginxConfig nginxConfig = new NginxConfig(upstreamList, locationList); try { logger.info("刷新Nginx配置文件开始 nginxConfig:{}", JSON.toJSONString(nginxConfig)); loadBalancingService.updateNginxConfig(nginxConfig); logger.info("刷新Nginx配置文件完成"); } catch (Exception e) { logger.error("刷新Nginx配置文件失败", e); } } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/interfaces/LoadBalancingMange.java
Java
mit
2,390
package zack.gateway.center.interfaces; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DuplicateKeyException; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import zack.gateway.center.application.IConfigManageService; import zack.gateway.center.application.IMessageService; import zack.gateway.center.application.IRegisterManageService; import zack.gateway.center.domain.register.model.vo.ApplicationInterfaceMethodVO; import zack.gateway.center.domain.register.model.vo.ApplicationInterfaceVO; import zack.gateway.center.domain.register.model.vo.ApplicationSystemVO; import zack.gateway.center.infrastructure.common.ResponseCode; import zack.gateway.center.infrastructure.common.Result; import javax.annotation.Resource; /** * @author zack * @description RPC 服务注册管理 */ @RestController @RequestMapping("/wg/admin/register") public class RpcRegisterManage { private Logger logger = LoggerFactory.getLogger(RpcRegisterManage.class); @Resource private IRegisterManageService registerManageService; @Resource private IConfigManageService configManageService; @Resource IMessageService messageService; @PostMapping(value = "registerApplication", produces = "application/json;charset=utf-8") public Result<Boolean> registerApplication(@RequestParam String systemId, @RequestParam String systemName, @RequestParam String systemType, @RequestParam String systemRegistry) { try { logger.info("注册应用服务 systemId:{}", systemId); ApplicationSystemVO applicationSystemVO = new ApplicationSystemVO(); applicationSystemVO.setSystemId(systemId); applicationSystemVO.setSystemName(systemName); applicationSystemVO.setSystemType(systemType); applicationSystemVO.setSystemRegistry(systemRegistry); registerManageService.registerApplication(applicationSystemVO); return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), true); } catch (DuplicateKeyException e) { logger.warn("注册应用服务重复 systemId:{}", systemId, e); return new Result<>(ResponseCode.INDEX_DUP.getCode(), e.getMessage(), true); } catch (Exception e) { logger.error("注册应用服务失败 systemId:{}", systemId, e); return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), false); } } @PostMapping(value = "registerApplicationInterface", produces = "application/json;charset=utf-8") public Result<Boolean> registerApplicationInterface(@RequestParam String systemId, @RequestParam String interfaceId, @RequestParam String interfaceName, @RequestParam String interfaceVersion) { try { logger.info("注册应用接口 systemId:{} interfaceId:{}", systemId, interfaceId); ApplicationInterfaceVO applicationInterfaceVO = new ApplicationInterfaceVO(); applicationInterfaceVO.setSystemId(systemId); applicationInterfaceVO.setInterfaceId(interfaceId); applicationInterfaceVO.setInterfaceName(interfaceName); applicationInterfaceVO.setInterfaceVersion(interfaceVersion); registerManageService.registerApplicationInterface(applicationInterfaceVO); return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), true); } catch (DuplicateKeyException e) { logger.warn("注册应用接口重复 systemId:{} interfaceId:{}", systemId, interfaceId); return new Result<>(ResponseCode.INDEX_DUP.getCode(), e.getMessage(), true); } catch (Exception e) { logger.error("注册应用接口失败 systemId:{}", systemId, e); return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), false); } } @PostMapping(value = "registerApplicationInterfaceMethod", produces = "application/json;charset=utf-8") public Result<Boolean> registerApplicationInterfaceMethod(@RequestParam String systemId, @RequestParam String interfaceId, @RequestParam String methodId, @RequestParam String methodName, @RequestParam String parameterType, @RequestParam String uri, @RequestParam String httpCommandType, @RequestParam Integer auth) { try { logger.info("注册应用接口方法 systemId:{} interfaceId:{} methodId:{}", systemId, interfaceId, methodId); ApplicationInterfaceMethodVO applicationInterfaceVO = new ApplicationInterfaceMethodVO(); applicationInterfaceVO.setSystemId(systemId); applicationInterfaceVO.setInterfaceId(interfaceId); applicationInterfaceVO.setMethodId(methodId); applicationInterfaceVO.setMethodName(methodName); applicationInterfaceVO.setParameterType(parameterType); applicationInterfaceVO.setUri(uri); applicationInterfaceVO.setHttpCommandType(httpCommandType); applicationInterfaceVO.setAuth(auth); registerManageService.registerApplicationInterfaceMethod(applicationInterfaceVO); return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), true); } catch (DuplicateKeyException e) { logger.warn("注册应用接口重复 systemId:{} interfaceId:{}", systemId, interfaceId); return new Result<>(ResponseCode.INDEX_DUP.getCode(), e.getMessage(), true); } catch (Exception e) { logger.error("注册应用接口失败 systemId:{}", systemId, e); return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), false); } } /** * rpc应用通过sdk注册完毕system,interface,method后调用注册完毕事件,将消息发送到redis,供assist监听 * * @param systemId * @return */ @PostMapping(value = "registerEvent", produces = "application/json;charset=utf-8") public Result<Boolean> registerEvent(@RequestParam String systemId) { try { logger.info("应用信息注册完成通知 systemId:{}", systemId); String gatewayId = configManageService.queryGatewayDistributionGatewayBySystemId(systemId); messageService.pushMessage(gatewayId, systemId); return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), true); } catch (Exception e) { logger.error("应用信息注册完成通知失败 systemId:{}", systemId, e); return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), false); } } }
2301_82000044/my-api-gateway
my-api-gateway-center/src/main/java/zack/gateway/center/interfaces/RpcRegisterManage.java
Java
mit
7,617
docker run -p 8001:8001 \ -v /mnt/c/javaData/git_test/my-api-gateway-center/docs/data/nginx:/data/nginx \ -v /var/run/docker.sock:/var/run/docker.sock \ --name api-gateway-center \ -d \ my-api-gateway-center:1.0 CP4-LISTEN:8001,fork,reuseaddr UNIX-CONNECT:/var/run/docker.sock TCP4-LISTEN:8001,fork,reuseaddr UNIX-CONNECT:/var/run/docker.sock
2301_82000044/my-api-gateway
my-api-gateway-center/start.sh
Shell
mit
348
package zack.gateway.core.authorization; import io.jsonwebtoken.Claims; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; /** 网关认证领域 * @author A1793 */ public class GatewayAuthorizingRealm extends AuthorizingRealm { @Override public Class<?> getAuthenticationTokenClass() { return GatewayAuthorizingToken.class; } @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { try { // 验证解析是否报错 Claims claims = JwtUtil.decode(((GatewayAuthorizingToken) token).getJwt()); if (!token.getPrincipal().equals(claims.getSubject())) throw new AuthenticationException("无效令牌"); } catch (Exception e) { throw new AuthenticationException("无效令牌"); } return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), this.getName()); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/authorization/GatewayAuthorizingRealm.java
Java
mit
1,415
package zack.gateway.core.authorization; import org.apache.shiro.authc.AuthenticationToken; /** 网关认证token * @author A1793 */ public class GatewayAuthorizingToken implements AuthenticationToken { private static final long serialVersionUID = 1L; private String uid; private String jwt; public GatewayAuthorizingToken() { } public GatewayAuthorizingToken(String uid,String jwt) { this.uid = uid; this.jwt = jwt; } @Override public Object getPrincipal() { return uid; } @Override public Object getCredentials() { return jwt; } public String getJwt(){ return jwt; } public void setUid(String uid) { this.uid = uid; } public void setJwt(String jwt) { this.jwt = jwt; } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/authorization/GatewayAuthorizingToken.java
Java
mit
816
package zack.gateway.core.authorization; /**认证服务接口 * @author A1793 */ public interface IAuth { public boolean validate(String id,String token); }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/authorization/IAuth.java
Java
mit
166
package zack.gateway.core.authorization; import com.alibaba.fastjson2.JSON; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @author A1793 */ public class JwtUtil { private static final String signingKey = "B*B^5Fe"; public static String encode(String issuer,long ttlMills,Map<String,Object> claims){ if(claims == null){ claims = new HashMap<String,Object>(); } long currentTimeMillis = System.currentTimeMillis(); Date date = new Date(currentTimeMillis); //先设置荷载claims JwtBuilder builder = Jwts.builder() //设置荷载信息 .setClaims(claims) //设置签发日期 .setIssuedAt(date) //设置签发人 .setSubject(issuer) //设置签发算法和密钥 .signWith(SignatureAlgorithm.HS256,signingKey); //设置token的过期时间 if(ttlMills>0){ long expMillis = currentTimeMillis + ttlMills; Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); } public static Claims decode(String token){ return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token).getBody(); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/authorization/JwtUtil.java
Java
mit
1,478
package zack.gateway.core.authorization.auth; import zack.gateway.core.authorization.GatewayAuthorizingToken; import zack.gateway.core.authorization.IAuth; import org.apache.shiro.SecurityUtils; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; /**认证服务 * @author A1793 */ public class AuthService implements IAuth { private Subject subject; public AuthService() { //根据本地配置,从security工厂生成manager IniSecurityManagerFactory iniSecurityManagerFactory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = iniSecurityManagerFactory.getInstance(); SecurityUtils.setSecurityManager(securityManager); this.subject = SecurityUtils.getSubject(); } @Override public boolean validate(String id, String token) { try{ subject.login(new GatewayAuthorizingToken(id, token)); return subject.isAuthenticated(); }finally { subject.logout(); } } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/authorization/auth/AuthService.java
Java
mit
1,119
package zack.gateway.core.bind; import zack.gateway.core.executor.result.SessionResult; import java.util.Map; /**统一泛化调用接口 * @author A1793 */ public interface IGenericReference { public SessionResult $invoke(Map<String,Object> args); }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/bind/IGenericReference.java
Java
mit
262
package zack.gateway.core.bind; import zack.gateway.core.mapping.HttpCommandType; import zack.gateway.core.session.Configuration; import zack.gateway.core.session.GatewaySession; import java.lang.reflect.Method; import java.util.Map; /**绑定映射方法,最底层走session会话,session中调用rpc服务 * @author A1793 */ public class MapperMethod { private String methodName; private HttpCommandType command; public MapperMethod(String uri, Method method, Configuration config) { this.methodName = config.getHttpStatement(uri).getMethodName(); this.command = config.getHttpStatement(uri).getHttpCommandType(); } public Object execute(GatewaySession session, Map<String,Object> args) { Object result = null; switch (command) { case GET: result = session.get(methodName, args); break; case POST: result = session.post(methodName, args); break; case PUT: break; case DELETE: break; default: throw new RuntimeException("Unknown execution method for: " + command); } return result; } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/bind/MapperMethod.java
Java
mit
1,242
package zack.gateway.core.bind; import zack.gateway.core.session.GatewaySession; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; import java.util.Map; /**映射代理 * @author A1793 */ public class MapperProxy implements MethodInterceptor { private GatewaySession session; private String uri; public MapperProxy(String uri, GatewaySession session) { this.uri = uri; this.session = session; } @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { MapperMethod mapperMethod = new MapperMethod(uri, method, session.getConfiguration()); return mapperMethod.execute(session,(Map<String,Object>) objects[0]); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/bind/MapperProxy.java
Java
mit
812
package zack.gateway.core.bind; import zack.gateway.core.mapping.HttpStatement; import zack.gateway.core.session.GatewaySession; import net.sf.cglib.core.Signature; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.InterfaceMaker; import org.objectweb.asm.Type; import java.util.HashMap; import java.util.Map; /**映射代理工厂,为session和http调用创建代理对象 * @author A1793 */ public class MapperProxyFactory { private String uri; private final Map<String,IGenericReference> mapperProxyMap = new HashMap(); public MapperProxyFactory(String uri) { this.uri = uri; } public IGenericReference newInstance(GatewaySession session) { MapperProxy mapperProxy = new MapperProxy(uri, session); HttpStatement httpStatement = session.getConfiguration().getHttpStatement(uri); InterfaceMaker interfaceMaker = new InterfaceMaker(); interfaceMaker.add(new Signature(httpStatement.getMethodName(), Type.getType(String.class),new Type[]{Type.getType(String.class)}),null); Class<?> interfaceClass = interfaceMaker.create(); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Object.class); enhancer.setInterfaces(new Class[]{interfaceClass, IGenericReference.class}); enhancer.setCallback(mapperProxy); return (IGenericReference) enhancer.create(); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/bind/MapperProxyFactory.java
Java
mit
1,397
package zack.gateway.core.bind; import zack.gateway.core.mapping.HttpStatement; import zack.gateway.core.session.Configuration; import zack.gateway.core.session.GatewaySession; import java.util.HashMap; import java.util.Map; /**泛化调用注册机,一个uri对应一个代理工厂 * @author A1793 */ public class MapperRegistry { private Configuration configuration; public MapperRegistry(Configuration configuration) { this.configuration = configuration; } private final Map<String,MapperProxyFactory> knownMappers = new HashMap<String,MapperProxyFactory>(); public IGenericReference getMapper(String uri, GatewaySession session) { MapperProxyFactory mapperProxyFactory = knownMappers.get(uri); if(mapperProxyFactory == null) { throw new RuntimeException("Uri " + uri + " is not known to the MapperRegistry."); } try{ return mapperProxyFactory.newInstance(session); }catch(Exception e){ throw new RuntimeException("Error getting mapper instance. Cause: " + e, e); } } /** * 注册http调用信息, * @param statement */ public void addMapper(HttpStatement statement) { String uri = statement.getUri(); if(knownMappers.containsKey(uri)) { } knownMappers.put(uri,new MapperProxyFactory(uri)); configuration.addHttpStatement(statement); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/bind/MapperRegistry.java
Java
mit
1,438
package zack.gateway.core.datasource; /**连接 * @author A1793 */ public interface Connection { Object execute(String methodName,String[] parameterTypes,String[] parameterNames, Object[] args) ; }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/datasource/Connection.java
Java
mit
206
package zack.gateway.core.datasource; /**数据源(可以是rpc泛化调用,也是其他的数据源) * @author A1793 */ public interface DataSource { Connection getConnection(); }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/datasource/DataSource.java
Java
mit
194
package zack.gateway.core.datasource; import zack.gateway.core.session.Configuration; /**数据源工厂 * @author A1793 */ public interface DataSourceFactory { public void setProperties(Configuration configuration,String uri); DataSource getDataSource(); }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/datasource/DataSourceFactory.java
Java
mit
272
package zack.gateway.core.datasource; /**数据源类型 * @author A1793 */ public enum DataSourceType { DUBBO, HTTP; }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/datasource/DataSourceType.java
Java
mit
133
package zack.gateway.core.datasource.connection; import zack.gateway.core.datasource.Connection; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.utils.ReferenceConfigCache; import org.apache.dubbo.rpc.service.GenericService; /** * 与dubbo建立的数据源,进行rpc泛化接口的生成 * @author A1793 */ public class DubboConnection implements Connection { private final GenericService genericService; public DubboConnection(ApplicationConfig applicationConfig, RegistryConfig registryConfig , ReferenceConfig referenceConfig) { DubboBootstrap bootstrap = DubboBootstrap.getInstance(); bootstrap.application(applicationConfig).registry(registryConfig).reference(referenceConfig); ReferenceConfigCache cache = ReferenceConfigCache.getCache(); genericService = (GenericService) cache.get(referenceConfig); } @Override public Object execute(String methodName, String[] parameterTypes, String[] parameterNames, Object[] args) { return genericService.$invoke(methodName,parameterTypes,args); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/datasource/connection/DubboConnection.java
Java
mit
1,254
package zack.gateway.core.datasource.connection; import zack.gateway.core.datasource.Connection; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; /**封装http的POST请求 * @author A1793 */ public class HTTPConnection implements Connection { HttpClient httpClient; //请求方法 PostMethod postMethod; public HTTPConnection(String uri) { httpClient = new HttpClient(); //配置请求路径 postMethod = new PostMethod(uri); //设置请求头 //表示客户端(当前代码中的HTTPClient)可以接受任意类型的响应数据(如 JSON、XML、文本等) postMethod.setRequestHeader("accept","*/*"); //设置请求体格式 postMethod.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); postMethod.setRequestHeader("Connection", "keep-alive"); postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36"); } @Override public Object execute(String methodName, String[] parameterTypes, String[] parameterNames, Object[] args) { String res = " "; try{ //客户端执行请求 int code = httpClient.executeMethod(postMethod); if(code == 200){ res = postMethod.getResponseBodyAsString(); } }catch(Exception e){ e.printStackTrace(); } return res; } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/datasource/connection/HTTPConnection.java
Java
mit
1,566
package zack.gateway.core.datasource.unpooled; import zack.gateway.core.datasource.Connection; import zack.gateway.core.datasource.DataSource; import zack.gateway.core.datasource.DataSourceType; import zack.gateway.core.datasource.connection.DubboConnection; import zack.gateway.core.mapping.HttpStatement; import zack.gateway.core.session.Configuration; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.rpc.service.GenericService; /**非池化的数据源 * @author A1793 */ public class UnpooledDataSource implements DataSource { private Configuration configuration; private HttpStatement httpStatement; private DataSourceType type; @Override public Connection getConnection() { switch (type){ case HTTP://TODO ;break; case DUBBO: { //设置连接dubbo服务需要的信息 ApplicationConfig applicationConfig = configuration.getApplicationConfig(httpStatement.getApplication()); RegistryConfig registryConfig = configuration.getRegistryConfig(httpStatement.getApplication()); ReferenceConfig<GenericService> referenceConfig = configuration.getReferenceConfig(httpStatement.getInterfaceName()); return new DubboConnection(applicationConfig,registryConfig,referenceConfig); } } return null; } public void setConfiguration(Configuration configuration) { this.configuration = configuration; } public void setHttpStatement(HttpStatement httpStatement) { this.httpStatement = httpStatement; } public void setType(DataSourceType type) { this.type = type; } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/datasource/unpooled/UnpooledDataSource.java
Java
mit
1,826
package zack.gateway.core.datasource.unpooled; import zack.gateway.core.datasource.DataSource; import zack.gateway.core.datasource.DataSourceFactory; import zack.gateway.core.datasource.DataSourceType; import zack.gateway.core.session.Configuration; /**默认网关会话工厂,创建session * @author A1793 */ public class UnpooledDataSourceFactory implements DataSourceFactory { protected UnpooledDataSource dataSource; public UnpooledDataSourceFactory() { dataSource = new UnpooledDataSource(); } @Override public void setProperties(Configuration configuration, String uri) { dataSource.setHttpStatement(configuration.getHttpStatement(uri)); dataSource.setConfiguration(configuration); dataSource.setType(DataSourceType.DUBBO); } @Override public DataSource getDataSource() { return this.dataSource; } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/datasource/unpooled/UnpooledDataSourceFactory.java
Java
mit
893
package zack.gateway.core.executor; import zack.gateway.core.datasource.Connection; import zack.gateway.core.executor.result.SessionResult; import zack.gateway.core.mapping.HttpStatement; import zack.gateway.core.session.Configuration; import zack.gateway.core.type.SimpleTypeRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /**抽象的执行器基类,定义执行流程 * @author A1793 */ public abstract class BaseExecutor implements Executor { private Logger logger = LoggerFactory.getLogger(BaseExecutor.class); protected Connection connection; protected Configuration configuration; public BaseExecutor(Connection connection, Configuration configuration) { this.connection = connection; this.configuration = configuration; } @Override public SessionResult exec(HttpStatement httpStatement, Map<String, Object> parameters) { //可以拓展参数处理 String methodName = httpStatement.getMethodName(); String[] parameterType = new String[]{httpStatement.getParameterType()}; Object[] params = SimpleTypeRegistry.isSimpleType(httpStatement.getParameterType())? parameters.values().toArray():new Object[]{parameters}; try{ Object result = doExecute(methodName, parameterType, params); return SessionResult.buildSuccess(result); }catch(Exception e){ return SessionResult.buildError(e.getMessage()); } } protected abstract Object doExecute(String methodName,String[] parameterTypes,Object[] params ) ; }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/executor/BaseExecutor.java
Java
mit
1,624
package zack.gateway.core.executor; import zack.gateway.core.executor.result.SessionResult; import zack.gateway.core.mapping.HttpStatement; import java.util.Map; /**执行器,负责rpc连接,将rpc泛化调用与网关会话抽离 * @author A1793 */ public interface Executor { public SessionResult exec(HttpStatement httpStatement, Map<String,Object> parameters); }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/executor/Executor.java
Java
mit
381
package zack.gateway.core.executor; import zack.gateway.core.datasource.Connection; import zack.gateway.core.session.Configuration; /** * @author A1793 */ public class SimpleExecutor extends BaseExecutor { public SimpleExecutor(Connection connection,Configuration configuration) { super(connection,configuration); } @Override protected Object doExecute(String methodName, String[] parameterTypes, Object[] params) { return connection.execute(methodName,parameterTypes,new String[]{"ignore"},params); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/executor/SimpleExecutor.java
Java
mit
545
package zack.gateway.core.executor.result; /**执行结构 * @author A1793 */ public class SessionResult { private String code; private String info; private Object data; public SessionResult(String code, String info, Object data) { this.code = code; this.info = info; this.data = data; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public static SessionResult buildSuccess(Object data) { return new SessionResult("0000","调用成功",data); } public static SessionResult buildError(Object data) { return new SessionResult("0001","调用失败",data); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/executor/result/SessionResult.java
Java
mit
983
package zack.gateway.core.mapping; /**http请求类型 * @author A1793 */ public enum HttpCommandType { UNKNOWN, GET, POST, PUT, DELETE; }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/mapping/HttpCommandType.java
Java
mit
163
package zack.gateway.core.mapping; /**网关接口映射信息 * @author A1793 */ public class HttpStatement { /** 应用名称; */ private String application; /** 服务接口;RPC、其他 */ private String interfaceName; /** 服务方法;RPC#method */ private String methodName; /** 参数类型(RPC 限定单参数注册);new String[]{"java.lang.String"}、new String[]{"cn.bugstack.gateway.rpc.dto.XReq"} */ private String parameterType; /** 网关接口 */ private String uri; /** 接口类型;GET、POST、PUT、DELETE */ private HttpCommandType httpCommandType; /**该uri请求是否需要鉴权*/ private boolean isAuth; public HttpStatement(String application, String interfaceName, String methodName, String parameterType, String uri, HttpCommandType httpCommandType,boolean isAuth) { this.application = application; this.interfaceName = interfaceName; this.methodName = methodName; this.parameterType = parameterType; this.uri = uri; this.httpCommandType = httpCommandType; this.isAuth = isAuth; } public String getApplication() { return application; } public String getInterfaceName() { return interfaceName; } public String getMethodName() { return methodName; } public String getUri() { return uri; } public HttpCommandType getHttpCommandType() { return httpCommandType; } public String getParameterType() { return parameterType; } public boolean isAuth() { return isAuth; } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/mapping/HttpStatement.java
Java
mit
1,644
package zack.gateway.core.session; import zack.gateway.core.authorization.IAuth; import zack.gateway.core.authorization.auth.AuthService; import zack.gateway.core.bind.IGenericReference; import zack.gateway.core.bind.MapperRegistry; import zack.gateway.core.datasource.Connection; import zack.gateway.core.executor.Executor; import zack.gateway.core.executor.SimpleExecutor; import zack.gateway.core.mapping.HttpStatement; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.rpc.service.GenericService; import java.util.HashMap; import java.util.Map; /**会话生命周期配置 * @author A1793 */ public class Configuration { private String host = "127.0.0.1"; private int port = 7397; private int bossGroupSize = 1; private int workerGroupSize = 4; //泛化调用注册机 private final MapperRegistry mapperRegistry = new MapperRegistry(this); //鉴权配置 private final IAuth authService = new AuthService(); //存储压迫进行泛化调用的网关信息 private final Map<String, HttpStatement> httpStatements = new HashMap<>(); //当前工程的应用配置 private final Map<String, ApplicationConfig> applicationConfigMap = new HashMap<>(); //要访问的服务所在的注册中心的配置 private final Map<String, RegistryConfig> registryConfigMap = new HashMap<>(); //要调用的接口配置 private final Map<String, ReferenceConfig<GenericService>> referenceConfigMap = new HashMap<>(); public String getHost() { return host; } public int getPort() { return port; } public int getBossGroupSize() { return bossGroupSize; } public int getWorkerGroupSize() { return workerGroupSize; } public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } public void setBossGroupSize(int bossGroupSize) { this.bossGroupSize = bossGroupSize; } public void setWorkerGroupSize(int workerGroupSize) { this.workerGroupSize = workerGroupSize; } public Configuration() { // // ApplicationConfig:当前应用(网关)的身份配置,用于定义当前应用(这里指网关)的基本信息,告诉 Dubbo 框架 “我是谁”。 // //代码中配置了 // //application.setName("api-gateway-test"): // // 设置当前应用的名称为 api-gateway-test(相当于网关的 “身份证”,Dubbo 会用这个名称在注册中心标识当前应用)。 // //application.setQosEnable(false): // // 关闭 Dubbo 的 QoS(Quality of Service,服务治理)功能(QoS 用于远程管理服务,网关作为调用方可能不需要开启)。 // ApplicationConfig application = new ApplicationConfig(); // application.setName("api-gateway-test"); // application.setQosEnable(false); // //RegistryConfig:注册中心配置,用于定义远程服务的注册中心信息,告诉 Dubbo 框架 “去哪里找远程服务”。 // //代码中配置了: // //registry.setAddress("zookeeper://127.0.0.1:2181"): // // 设置注册中心的地址为本地 ZooKeeper 服务(127.0.0.1:2181)。Dubbo 通常依赖 ZooKeeper 作为注册中心,存储服务提供者的地址信息。 // //registry.setRegister(false): // // 设置当前应用(网关)“不注册自己” 到注册中心。因为网关是服务消费者(只调用其他服务,不提供服务),所以不需要把自己注册到注册中心。 // //作用:网关通过这个配置连接注册中心,从而发现并获取远程服务(如 IActivityBooth)的提供者地址。 // RegistryConfig registry = new RegistryConfig(); // registry.setAddress("zookeeper://122.51.38.***:2181?timeout=600000"); // registry.setRegister(false); // //ReferenceConfig<GenericService>:远程服务的引用配置,用于定义要调用的远程服务的具体信息,告诉 Dubbo 框架 “我要调用哪个服务”。 // //代码中配置了: // //reference.setInterface("cn.bugstack.gateway.rpc.IActivityBooth"): // // 指定要调用的远程服务接口的全类名(即远程服务的 “唯一标识”,Dubbo 通过接口名找到对应的服务)。 // //reference.setVersion("1.0.0"): // // 指定要调用的服务版本(同一个接口可能有多个版本,通过版本号区分,避免冲突)。 // //reference.setGeneric("true"): // // 开启泛化调用模式(GenericService 是 Dubbo 泛化调用的接口)。 // // 泛化调用允许在不依赖远程服务接口类(即不需要引入 IActivityBooth.class 文件)的情况下调用服务, // // 这对网关非常重要(网关不需要依赖所有服务的接口包)。 // //作用:这是网关调用远程服务的 “直接配置”,Dubbo 根据这些信息生成服务代理,让网关可以通过 GenericService 接口调用远程服务的方法。 // ReferenceConfig<GenericService> reference = new ReferenceConfig<>(); // reference.setInterface("cn.bugstack.gateway.rpc.IActivityBooth"); // reference.setVersion("1.0.0"); // reference.setGeneric("true"); // // applicationConfigMap.put("api-gateway-test", application); // registryConfigMap.put("api-gateway-test", registry); // referenceConfigMap.put("cn.bugstack.gateway.rpc.IActivityBooth", reference); } public synchronized void registryConfig(String applicationName, String address, String interfaceName, String version) { if (applicationConfigMap.get(applicationName) == null) { ApplicationConfig application = new ApplicationConfig(); application.setName(applicationName); application.setQosEnable(false); applicationConfigMap.put(applicationName, application); } if (registryConfigMap.get(applicationName) == null) { RegistryConfig registry = new RegistryConfig(); registry.setAddress(address); registry.setRegister(false); registryConfigMap.put(applicationName, registry); } if (referenceConfigMap.get(interfaceName) == null) { ReferenceConfig<GenericService> reference = new ReferenceConfig<>(); reference.setInterface(interfaceName); reference.setVersion(version); reference.setGeneric("true"); referenceConfigMap.put(interfaceName, reference); } } public ApplicationConfig getApplicationConfig(String applicationName) { return applicationConfigMap.get(applicationName); } public RegistryConfig getRegistryConfig(String applicationName) { return registryConfigMap.get(applicationName); } public ReferenceConfig<GenericService> getReferenceConfig(String interfaceName) { return referenceConfigMap.get(interfaceName); } public void addMapper(HttpStatement httpStatement) { mapperRegistry.addMapper(httpStatement); } public IGenericReference getMapper(String uri,GatewaySession gatewaySession) { return mapperRegistry.getMapper(uri,gatewaySession); } public void addHttpStatement(HttpStatement httpStatement) { httpStatements.put(httpStatement.getUri(), httpStatement); } public HttpStatement getHttpStatement(String uri) { return httpStatements.get(uri); } public Executor newExecutor(Connection connection){ return new SimpleExecutor(connection,this); } public boolean authValidate(String uid,String token ) { return authService.validate(uid,token); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/session/Configuration.java
Java
mit
7,928
package zack.gateway.core.session; import zack.gateway.core.bind.IGenericReference; import java.util.Map; /**用户处理http请求 * @author A1793 */ public interface GatewaySession { //http的get请求转为rpc Object get(String methodName, Map<String,Object> parameter); //http的post请求转为rpc Object post(String methodName, Map<String,Object> parameter); IGenericReference getMapper(); Configuration getConfiguration(); }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/session/GatewaySession.java
Java
mit
463
package zack.gateway.core.session; import java.util.concurrent.ExecutionException; /**泛化调用会话工厂接口 * @author A1793 */ public interface GatewaySessionFactory { public GatewaySession openSession(String uri) throws ExecutionException, InterruptedException; }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/session/GatewaySessionFactory.java
Java
mit
283
package zack.gateway.core.session.defaults; import zack.gateway.core.bind.IGenericReference; import zack.gateway.core.executor.Executor; import zack.gateway.core.mapping.HttpStatement; import zack.gateway.core.session.Configuration; import zack.gateway.core.session.GatewaySession; import java.util.Map; /**默认网关会话实现类,负责与rpc进行连接 * @author A1793 */ public class DefaultGatewaySession implements GatewaySession { private Configuration configuration; private String uri; private Executor executor; public DefaultGatewaySession(Configuration configuration,String uri,Executor executor) { this.configuration = configuration; this.executor = executor; this.uri = uri; } /** * 获取数据源连接 * @param methodName * @param parameters * @return */ @Override public Object get(String methodName, Map<String,Object> parameters) { HttpStatement httpStatement = configuration.getHttpStatement(uri); try { return executor.exec(httpStatement, parameters); } catch (Exception e) { throw new RuntimeException("Error exec get. Cause: " + e); } } @Override public Object post(String methodName, Map<String, Object> parameter) { return get(methodName, parameter); } @Override public IGenericReference getMapper() { return configuration.getMapper(uri,this); } @Override public Configuration getConfiguration() { return configuration; } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/session/defaults/DefaultGatewaySession.java
Java
mit
1,566
package zack.gateway.core.session.defaults; import zack.gateway.core.datasource.DataSource; import zack.gateway.core.datasource.unpooled.UnpooledDataSourceFactory; import zack.gateway.core.executor.Executor; import zack.gateway.core.session.Configuration; import zack.gateway.core.session.GatewaySession; import zack.gateway.core.session.GatewaySessionFactory; import java.util.concurrent.ExecutionException; /**网关会话工厂,开启rpc调用会话 * @author A1793 */ public class DefaultGatewaySessionFactory implements GatewaySessionFactory { private Configuration configuration; public DefaultGatewaySessionFactory(Configuration configuration) { this.configuration = configuration; } public Configuration getConfiguration() { return configuration; } /** * 建立数据源,提供給session,让他创建连接,进行rpc调用 * @param uri * @return * @throws ExecutionException * @throws InterruptedException */ @Override public GatewaySession openSession(String uri) throws ExecutionException, InterruptedException { UnpooledDataSourceFactory unpooledDataSourceFactory = new UnpooledDataSourceFactory(); unpooledDataSourceFactory.setProperties(configuration,uri); DataSource dataSource = unpooledDataSourceFactory.getDataSource(); Executor executor = configuration.newExecutor(dataSource.getConnection()); return new DefaultGatewaySession(configuration,uri,executor); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/session/defaults/DefaultGatewaySessionFactory.java
Java
mit
1,520
package zack.gateway.core.socket; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.util.concurrent.ExecutionException; /**会话基类 * @author A1793 */ public abstract class BaseHandler<T> extends SimpleChannelInboundHandler<T> { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, T t) throws Exception { session(channelHandlerContext,channelHandlerContext.channel(),t); } protected abstract void session(ChannelHandlerContext channelHandlerContext, final Channel channel, T t) throws ExecutionException, InterruptedException; }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/socket/BaseHandler.java
Java
mit
689
package zack.gateway.core.socket; import zack.gateway.core.session.Configuration; import zack.gateway.core.session.GatewaySessionFactory; import zack.gateway.core.session.defaults.DefaultGatewaySessionFactory; import zack.gateway.core.socket.handlers.AuthorizationHandler; import zack.gateway.core.socket.handlers.GatewayServerHandler; import zack.gateway.core.socket.handlers.ProtocolDataHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; /** * @author A1793 */ public class GatewayChannelInitializer extends ChannelInitializer<SocketChannel> { private final Configuration configuration; private final DefaultGatewaySessionFactory gatewaySessionFactory; public GatewayChannelInitializer(Configuration configuration, DefaultGatewaySessionFactory gatewaySessionFactory) { this.configuration = configuration; this.gatewaySessionFactory = gatewaySessionFactory; } @Override protected void initChannel(SocketChannel channel) throws Exception { //加入请求的解码器 channel.pipeline().addLast(new HttpRequestDecoder()); //加入响应的编码器 channel.pipeline().addLast(new HttpResponseEncoder()); //加入处理请求体的解码器 channel.pipeline().addLast(new HttpObjectAggregator(1024*1024)); //加入会话的处理器 channel.pipeline().addLast(new GatewayServerHandler(configuration)); channel.pipeline().addLast(new AuthorizationHandler(configuration)); channel.pipeline().addLast(new ProtocolDataHandler(gatewaySessionFactory)); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/socket/GatewayChannelInitializer.java
Java
mit
1,797
package zack.gateway.core.socket; import zack.gateway.core.session.Configuration; import zack.gateway.core.session.GatewaySessionFactory; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import zack.gateway.core.session.defaults.DefaultGatewaySessionFactory; import java.net.InetSocketAddress; import java.util.concurrent.Callable; /**会话服务器 * @author A1793 */ public class GatewaySocketServer implements Callable<Channel> { private Logger logger = LoggerFactory.getLogger(GatewaySocketServer.class); private final Configuration configuration; private DefaultGatewaySessionFactory gatewaySessionFactory; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private Channel channel; public GatewaySocketServer(Configuration configuration, DefaultGatewaySessionFactory gatewaySessionFactory) { this.configuration = configuration; this.gatewaySessionFactory = gatewaySessionFactory; } public void initEventLoopGroup() { bossGroup = new NioEventLoopGroup( configuration.getBossGroupSize()); workerGroup = new NioEventLoopGroup( configuration.getWorkerGroupSize()); } /** * 将会话服务启动放到线程中,不阻塞主线程 * @return * @throws Exception */ @Override public Channel call() throws Exception { ChannelFuture channelFuture = null; initEventLoopGroup(); try{ ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) .childHandler(new GatewayChannelInitializer(configuration,gatewaySessionFactory)); channelFuture = bootstrap.bind(new InetSocketAddress(configuration.getPort())).syncUninterruptibly(); channel = channelFuture.channel(); }catch (Exception e){ logger.error("socket server start error.", e); }finally{ if (null != channelFuture && channelFuture.isSuccess()) { logger.info("socket server start done."); } else { logger.error("socket server start error."); } } return channel; } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/socket/GatewaySocketServer.java
Java
mit
2,615
package zack.gateway.core.socket.agreement; import zack.gateway.core.mapping.HttpStatement; import io.netty.util.AttributeKey; /**协议参数常量 * @author A1793 */ public class AgreementConstants { //AttributeKey是 Netty 提供的用于在Channel或ChannelHandlerContext上绑定自定义属性的工具类。 // 通过它可以在 Channel 的生命周期内存储和读取数据,实现不同 Handler 之间的数据传递(无需通过方法参数显式传递)。 public static final AttributeKey<HttpStatement> HTTP_STATEMENT = AttributeKey.valueOf("HttpStatement"); public enum ResponseCode{ // 访问成功 _200("200","访问成功"), // 后端接收数据的数据类型不匹配 ,比如前端传送的数据时string,后端使用的是Integer数据类型接收,此时就会包以上错误 _400("400","接收数据的数据类型不匹配"), // (禁止) 服务器拒绝请求。资源不可用,服务器理解客户的请求,但拒绝处理它。 // 通常由于服务器上文件或目录的权限设置导致,比如IIS或者apache设置了访问权限不当。 _403("403","服务器拒绝请求"), // (未找到) 服务器找不到请求的网页;输入链接有误。 // 第一个4表示客户端出错,第二个 0 表示你把网址打错了,最后的那个4表示 “Not Found”,即找不到网页。 _404("404","服务器找不到请求的网页,输入链接有误"), // (服务器内部错误) 服务器遇到错误,无法完成请求。 _500("500","服务器遇到错误,无法完成请求"), // (错误网关) 服务器作为网关或代理,从上游服务器收到无效响应。如 RPC 提供方宕机。 _502("502","服务器作为网关或代理,从上游服务器收到无效响应"); private String code; private String info; ResponseCode(String code, String info) { this.code = code; this.info = info; } public String getCode() { return code; } public String getInfo() { return info; } } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/socket/agreement/AgreementConstants.java
Java
mit
2,222
package zack.gateway.core.socket.agreement; /**网关结果消息 * @author A1793 */ public class GatewayResultMessage { String code; String info; String node; Object data; public GatewayResultMessage(String code, String info, Object data) { this.code = code; this.info = info; this.data = data; } public static GatewayResultMessage buildSuccess(Object data) { return new GatewayResultMessage(AgreementConstants.ResponseCode._200.getCode(), AgreementConstants.ResponseCode._200.getInfo(), data); } public static GatewayResultMessage buildError(String code, String info) { return new GatewayResultMessage(code,info,null); } public GatewayResultMessage setNode(String node) { this.node = node; return this; } public String getCode() { return code; } public String getInfo() { return info; } public Object getData() { return data; } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/socket/agreement/GatewayResultMessage.java
Java
mit
994
package zack.gateway.core.socket.agreement; import com.alibaba.fastjson2.JSON; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.handler.codec.http.multipart.Attribute; import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Optional; /**请求参数解析器 * @author A1793 */ public class RequestParser { private FullHttpRequest request; public RequestParser(FullHttpRequest request) { this.request = request; } public String getUri(){ String uri = request.uri(); //如果请求参数拼接到了uri上面 if(uri.indexOf("?") != -1){ uri = uri.substring(0, uri.indexOf("?")); } return uri; } public Map<String,Object> parse() { HttpMethod method = request.method(); String contentType = getContentType(); Map<String, Object> parammeters = new HashMap<>(); if (method == HttpMethod.GET) { //get请求的额参数都拼接在uri中 QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri()); //将 xxx=yyy解析成<k,v>键值对加到map里 queryStringDecoder.parameters().forEach((k, v) -> { parammeters.put(k, v.get(0)); }); return parammeters; } else if (method == HttpMethod.POST) { switch (contentType) { case "application/json": { ByteBuf byteBuf = request.content().retain(); if (byteBuf.isReadable()) { String content = byteBuf.toString(StandardCharsets.UTF_8); return JSON.parseObject(content); } };break; case "multipart/form-data": { HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request); decoder.offer(request); decoder.getBodyHttpDatas().forEach(data -> { Attribute value = (Attribute) data; try { parammeters.put(data.getName(), value.getValue()); } catch (Exception e) { } ; }); };return parammeters; default: throw new RuntimeException("未实现的协议类型 Content-Type:" + contentType); } } throw new RuntimeException("未实现的请求类型 HttpMethod:" + method); } private String getContentType() { Optional<Map.Entry<String, String>> header = request.headers() .entries().stream().filter(entry -> entry.getKey().equals("Content-Type")).findAny(); Map.Entry<String, String> entry = header.orElse(null); assert entry != null; String value = entry.getValue(); int index = value.indexOf(";"); if(index >0){ return value.substring(0,index); }else{ return value; } } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/socket/agreement/RequestParser.java
Java
mit
3,318
package zack.gateway.core.socket.agreement; import com.alibaba.fastjson.JSON; import io.netty.handler.codec.http.*; /**响应结果封装 * @author A1793 */ public class ResponseParser { public DefaultFullHttpResponse parse(Object result) { // 返回信息处理 DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); // 设置回写数据 response.content().writeBytes(JSON.toJSONString(result).getBytes()); // 头部信息设置 HttpHeaders heads = response.headers(); // 返回内容类型 heads.add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON + "; charset=UTF-8"); // 响应体的长度 heads.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); // 配置持久连接 heads.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); // 配置跨域访问 heads.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); heads.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, "*"); heads.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE"); heads.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); return response; } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/socket/agreement/ResponseParser.java
Java
mit
1,309
package zack.gateway.core.socket.handlers; import zack.gateway.core.mapping.HttpStatement; import zack.gateway.core.session.Configuration; import zack.gateway.core.socket.BaseHandler; import zack.gateway.core.socket.agreement.AgreementConstants; import zack.gateway.core.socket.agreement.GatewayResultMessage; import zack.gateway.core.socket.agreement.ResponseParser; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutionException; /**鉴权处理器 * @author A1793 */ public class AuthorizationHandler extends BaseHandler<FullHttpRequest> { private final Logger logger = LoggerFactory.getLogger(AuthorizationHandler.class); private final Configuration configuration; public AuthorizationHandler(Configuration configuration) { this.configuration = configuration; } @Override protected void session(ChannelHandlerContext ctx, Channel channel, FullHttpRequest request) throws ExecutionException, InterruptedException { try{ HttpStatement httpStatement = channel.attr(AgreementConstants.HTTP_STATEMENT).get(); //判断该uri是否需要鉴权 if( httpStatement.isAuth()){ String uid = request.headers().get("uid"); String token = request.headers().get("token"); //鉴权 if (null == token || "".equals(token)) { DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResultMessage.buildError(AgreementConstants.ResponseCode._400.getCode(), "对不起,你的 token 不合法!")); channel.writeAndFlush(response); } boolean status = configuration.authValidate(uid, token); if(status){ request.retain(); ctx.fireChannelRead(request); }else { DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResultMessage.buildError(AgreementConstants.ResponseCode._403.getCode(), "对不起,你无权访问此接口!")); channel.writeAndFlush(response); } }else{ //不需要鉴权的放行 request.retain(); ctx.fireChannelRead(request); } }catch(Exception e){ // 4. 封装返回结果 DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResultMessage.buildError(AgreementConstants.ResponseCode._500.getCode(), "网关协议调用失败!" + e.getMessage())); channel.writeAndFlush(response); } } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/socket/handlers/AuthorizationHandler.java
Java
mit
2,815
package zack.gateway.core.socket.handlers; import zack.gateway.core.mapping.HttpStatement; import zack.gateway.core.socket.BaseHandler; import zack.gateway.core.session.Configuration; import zack.gateway.core.socket.agreement.AgreementConstants; import zack.gateway.core.socket.agreement.GatewayResultMessage; import zack.gateway.core.socket.agreement.RequestParser; import zack.gateway.core.socket.agreement.ResponseParser; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutionException; /**网络协议处理器,給通道添加属性 * @author A1793 */ public class GatewayServerHandler extends BaseHandler<FullHttpRequest> { private Logger logger = LoggerFactory.getLogger(this.getClass()); private final Configuration configuration; public GatewayServerHandler(Configuration configuration) { this.configuration = configuration; } @Override protected void session(ChannelHandlerContext ctx, Channel channel, FullHttpRequest fullHttpRequest) throws ExecutionException, InterruptedException { try{ //参数处理 RequestParser requestParser = new RequestParser(fullHttpRequest); String uri = requestParser.getUri(); //获取网关接口映射信息并加入到通道的属性中 HttpStatement httpStatement = configuration.getHttpStatement(uri); channel.attr(AgreementConstants.HTTP_STATEMENT).set(httpStatement); //放行到下个处理器 fullHttpRequest.retain(); ctx.fireChannelRead(fullHttpRequest); }catch (Exception e){ // 4. 封装返回结果 DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResultMessage.buildError(AgreementConstants.ResponseCode._500.getCode(), "网关协议调用失败!" + e.getMessage())); channel.writeAndFlush(response); } } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/socket/handlers/GatewayServerHandler.java
Java
mit
2,047
package zack.gateway.core.socket.handlers; import zack.gateway.core.executor.result.SessionResult; import zack.gateway.core.session.GatewaySession; import zack.gateway.core.session.GatewaySessionFactory; import zack.gateway.core.session.defaults.DefaultGatewaySessionFactory; import zack.gateway.core.socket.BaseHandler; import zack.gateway.core.socket.agreement.AgreementConstants; import zack.gateway.core.socket.agreement.GatewayResultMessage; import zack.gateway.core.socket.agreement.RequestParser; import zack.gateway.core.socket.agreement.ResponseParser; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.ExecutionException; public class ProtocolDataHandler extends BaseHandler<FullHttpRequest> { private final Logger logger = LoggerFactory.getLogger(GatewayServerHandler.class); private final DefaultGatewaySessionFactory gatewaySessionFactory; public ProtocolDataHandler(DefaultGatewaySessionFactory gatewaySessionFactory) { this.gatewaySessionFactory = gatewaySessionFactory; } @Override protected void session(ChannelHandlerContext channelHandlerContext, Channel channel, FullHttpRequest request) throws ExecutionException, InterruptedException { logger.info("网关接收请求 uri:{} method:{}", request.uri(), request.method()); // 返回信息控制:简单处理 RequestParser parser = new RequestParser(request); String uri = parser.getUri(); Map<String, Object> requestObj = parser.parse(); //获取rpc会话 GatewaySession gatewaySession = gatewaySessionFactory.openSession(uri); // 服务泛化调用 SessionResult result = gatewaySession.getMapper().$invoke(requestObj) ; DefaultFullHttpResponse response = new ResponseParser().parse(result.getCode().equals("0000") ? GatewayResultMessage.buildSuccess(result.getData()).setNode(node()): GatewayResultMessage.buildError(AgreementConstants.ResponseCode._404.getCode(), "网关协议调用失败!").setNode(node()) ); channel.writeAndFlush(response); } private String node(){ return gatewaySessionFactory.getConfiguration().getHost() + ":" + gatewaySessionFactory.getConfiguration().getPort(); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/socket/handlers/ProtocolDataHandler.java
Java
mit
2,597
package zack.gateway.core.type; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import java.util.HashSet; import java.util.Set; /**基本类型注册表 * @author A1793 */ public class SimpleTypeRegistry { public final static Set<String> SIMPLE_TYPE_SET = new HashSet<String>(); static { SIMPLE_TYPE_SET.add(String.class.getName()); SIMPLE_TYPE_SET.add(Byte.class.getName()); SIMPLE_TYPE_SET.add(Short.class.getName()); SIMPLE_TYPE_SET.add(Character.class.getName()); SIMPLE_TYPE_SET.add(Integer.class.getName()); SIMPLE_TYPE_SET.add(Long.class.getName()); SIMPLE_TYPE_SET.add(Float.class.getName()); SIMPLE_TYPE_SET.add(Double.class.getName()); SIMPLE_TYPE_SET.add(Boolean.class.getName()); SIMPLE_TYPE_SET.add(Date.class.getName()); SIMPLE_TYPE_SET.add(Class.class.getName()); SIMPLE_TYPE_SET.add(BigInteger.class.getName()); SIMPLE_TYPE_SET.add(BigDecimal.class.getName()); } public SimpleTypeRegistry() { } public static boolean isSimpleType(String type) { return SIMPLE_TYPE_SET.contains(type); } }
2301_82000044/my-api-gateway
my-api-gateway-core/src/main/java/zack/gateway/core/type/SimpleTypeRegistry.java
Java
mit
1,184
# 基础镜像 FROM openjdk:8-jre-slim # 作者 MAINTAINER zack # 配置 ENV PARAMS="" # 时区 ENV TZ=PRC RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 添加应用 ADD target/my-api-gateway-engine.jar /my-api-gateway-engine.jar # 执行镜像 ENTRYPOINT ["sh","-c","java -jar $JAVA_OPTS /my-api-gateway-engine.jar $PARAMS"]
2301_82000044/my-api-gateway
my-api-gateway-engine/Dockerfile
Dockerfile
mit
360
docker build -f ./Dockerfile -t zackzky/my-api-gateway-engine:1.3 .
2301_82000044/my-api-gateway
my-api-gateway-engine/build.sh
Shell
mit
67
#!/bin/bash # https://cr.console.aliyun.com/cn-hangzhou/instance/credentials # Ensure the script exits if any command fails set -e # Define variables for the registry and image ALIYUN_REGISTRY="crpi-f2fnckn7fe4gfuf0.cn-hangzhou.personal.cr.aliyuncs.com" NAMESPACE="zackzky" IMAGE_NAME="my-api-gateway-engine" IMAGE_TAG="1.1" # 读取本地配置文件 if [ -f ".local-config" ]; then source .local-config else echo ".local-config 文件不存在,请创建并填写 ALIYUN_USERNAME 和 ALIYUN_PASSWORD" exit 1 fi # Login to Aliyun Docker Registry echo "Logging into Aliyun Docker Registry..." docker login --username="${ALIYUN_USERNAME}" --password="${ALIYUN_PASSWORD}" $ALIYUN_REGISTRY # Tag the Docker image echo "Tagging the Docker image..." docker tag ${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG} ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG} # Push the Docker image to Aliyun echo "Pushing the Docker image to Aliyun..." docker push ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG} echo "Docker image pushed successfully! " echo "检出地址:docker pull ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}" echo "标签设置:docker tag ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG} ${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}" # Logout from Aliyun Docker Registry echo "Logging out from Aliyun Docker Registry..." docker logout $ALIYUN_REGISTRY
2301_82000044/my-api-gateway
my-api-gateway-engine/push.sh
Shell
mit
1,407
package zack; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) @Configurable public class Main { public static void main(String[] args) { SpringApplication.run(Main.class, args); } }
2301_82000044/my-api-gateway
my-api-gateway-engine/src/main/java/zack/Main.java
Java
mit
489
docker run -p 8902:8902 -p 7397:7397 \ -e PARAMS=" --sever.port=8902 --api-gateway.address=http://192.168.1.102:8901 --api-gateway.groupId=10001 --api-gateway.gatewayId=api-gateway-g4 --api-gateway.gatewayName=电商配送网关 --api-gateway.gatewayAddress=192.168.1.102:7397" \ --name api-gateway-engine-01 -d api-gateway-engine:1.0.0
2301_82000044/my-api-gateway
my-api-gateway-engine/start-01.sh
Shell
mit
368
docker run -p 8903:8903 -p 7398:7398 \ -e PARAMS=" --sever.port=8903 --api-gateway.address=http://192.168.1.102:8901 --api-gateway.groupId=10001 --api-gateway.gatewayId=api-gateway-g4 --api-gateway.gatewayName=电商配送网关 --api-gateway.gatewayAddress=192.168.1.102:7398" \ --name api-gateway-engine-02 -d api-gateway-engine:1.0.0
2301_82000044/my-api-gateway
my-api-gateway-engine/start-02.sh
Shell
mit
368
docker run -p 8904:8904 -p 7399:7399 \ -e PARAMS=" --sever.port=8904 --api-gateway.address=http://192.168.1.102:8901 --api-gateway.groupId=10001 --api-gateway.gatewayId=api-gateway-g4 --api-gateway.gatewayName=电商配送网关 --api-gateway.gatewayAddress=192.168.1.102:7399" \ --name api-gateway-engine-03 -d api-gateway-engine:1.0.0
2301_82000044/my-api-gateway
my-api-gateway-engine/start-03.sh
Shell
mit
368
docker run -p 8007:8007 -p 7399:7399 --name api-gateway-engine -d zackzky/my-api-gateway-engine:1.0
2301_82000044/my-api-gateway
my-api-gateway-engine/start.sh
Shell
mit
99
package zack.gateway.sdk; public class GatewayException extends RuntimeException { public GatewayException(String msg) { super(msg); } public GatewayException(String msg, Throwable cause) { super(msg, cause); } }
2301_82000044/my-api-gateway
my-api-gateway-sdk/src/main/java/zack/gateway/sdk/GatewayException.java
Java
mit
250
package zack.gateway.sdk.annotations; import java.lang.annotation.*; /** * @author A1793 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ApiProducerClazz { public String interfaceName() default " "; public String interfaceVersion() default " "; }
2301_82000044/my-api-gateway
my-api-gateway-sdk/src/main/java/zack/gateway/sdk/annotations/ApiProducerClazz.java
Java
mit
306
package zack.gateway.sdk.annotations; import java.lang.annotation.*; /** * @author A1793 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ApiProducerMethod { String methodName() default ""; String uri() default ""; String httpCommandType() default "GET"; int auth() default 0; }
2301_82000044/my-api-gateway
my-api-gateway-sdk/src/main/java/zack/gateway/sdk/annotations/ApiProducerMethod.java
Java
mit
348
package zack.gateway.sdk.application; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import zack.gateway.sdk.GatewayException; import zack.gateway.sdk.annotations.ApiProducerClazz; import zack.gateway.sdk.annotations.ApiProducerMethod; import zack.gateway.sdk.config.GatewaySDKAutoConfig; import zack.gateway.sdk.config.GatewaySDKProperties; import zack.gateway.sdk.domain.service.GatewayCenterService; import java.lang.reflect.Method; /** * @author A1793 */ public class GatewaySDKApplication implements BeanPostProcessor { private GatewaySDKProperties properties; private GatewayCenterService service; public GatewaySDKApplication(GatewaySDKProperties gatewaySDKProperties, GatewayCenterService gatewayCenterService) { this.properties = gatewaySDKProperties; this.service = gatewayCenterService; } /** * 在bean对象初始化之后对bean进行操作 * @param bean * @param beanName * @return * @throws BeansException */ @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { Logger logger = LoggerFactory.getLogger(GatewaySDKApplication.class); //处理接口信息 ApiProducerClazz apiProducerClazz = bean.getClass().getAnnotation(ApiProducerClazz.class); //没有注解说明不是对外提供服务的接口的实现类 if (apiProducerClazz == null){ return bean; } //注册系统应用信息 logger.info("\n应用注册:系统信息 \nsystemId: {} \nsystemName: {} \nsystemType: {} \nsystemRegistry: {}", properties.getSystemId(), properties.getSystemName(), "RPC", properties.getSystemRegistry()); service.doRegisterApplication(properties.getAddress(), properties.getSystemId(), properties.getSystemName(), "RPC", properties.getSystemRegistry()); //处理rpc应用下的接口 Class<?>[] interfaces = bean.getClass().getInterfaces(); //一个实现类对应一个对外接口 if(interfaces.length != 1){ throw new GatewayException(bean.getClass().getName() + "interfaces not one this is " + JSON.toJSONString(interfaces)); } String interfaceId = interfaces[0].getName(); logger.info("\n应用注册:接口信息 \nsystemId: {} \ninterfaceId: {} \ninterfaceName: {} \ninterfaceVersion: {}", properties.getSystemId(), interfaceId, apiProducerClazz.interfaceName(), apiProducerClazz.interfaceVersion()); String interfaceName = apiProducerClazz.interfaceName(); String interfaceVersion = apiProducerClazz.interfaceVersion(); service.doRegisterApplicationInterface(properties.getAddress(), properties.getSystemId(), interfaceId, interfaceName, interfaceVersion); //处理提供rpc服务的方法 Method[] methods = bean.getClass().getMethods(); for(Method method : methods){ ApiProducerMethod apiProducerMethod = method.getAnnotation(ApiProducerMethod.class); if(apiProducerMethod == null){ continue; } String methodId = method.getName(); String methodName = apiProducerMethod.methodName(); Class<?>[] parameterTypes = method.getParameterTypes(); StringBuilder parameterTypeBuilder = new StringBuilder(); for(Class<?> clazz : parameterTypes){ parameterTypeBuilder.append(clazz.getName()+","); } String parameterType = parameterTypeBuilder.toString().substring(0,parameterTypeBuilder.toString().lastIndexOf(",")); logger.info("\n应用注册:方法信息 \nsystemId: {} \ninterfaceId: {} \nmethodId: {} \nmethodName: {} \nparameterType: {} \nuri: {} \nhttpCommandType: {} \nauth: {}", properties.getSystemId(), interfaceId, method.getName(), apiProducerMethod.methodName(), parameterType, apiProducerMethod.uri(), apiProducerMethod.httpCommandType(), apiProducerMethod.auth()); String uri = apiProducerMethod.uri(); String httpCommandType = apiProducerMethod.httpCommandType(); Integer auth = apiProducerMethod.auth(); service.doRegisterApplicationInterfaceMethod(properties.getAddress(), properties.getSystemId(), interfaceId, methodId, methodName, parameterType, uri, httpCommandType, auth); } service.doRegisterEvent(properties.getAddress(), properties.getSystemId()); return bean; } }
2301_82000044/my-api-gateway
my-api-gateway-sdk/src/main/java/zack/gateway/sdk/application/GatewaySDKApplication.java
Java
mit
4,955
package zack.gateway.sdk.common; /** * @author A1793 */ public class Result<T> { String code; String info; T data; public Result(String code, String info, T data) { this.code = code; this.info = info; this.data = data; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
2301_82000044/my-api-gateway
my-api-gateway-sdk/src/main/java/zack/gateway/sdk/common/Result.java
Java
mit
651
package zack.gateway.sdk.config; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import zack.gateway.sdk.application.GatewaySDKApplication; import zack.gateway.sdk.domain.service.GatewayCenterService; /** * @author A1793 */ @Configuration @EnableConfigurationProperties({GatewaySDKProperties.class}) @ConditionalOnProperty( prefix = "api-gateway-sdk", name = "enable", havingValue = "true", matchIfMissing = true ) public class GatewaySDKAutoConfig { @Bean public GatewayCenterService gatewayCenterService(){ return new GatewayCenterService(); } @Bean public GatewaySDKApplication gatewaySDKApplication(GatewaySDKProperties gatewaySDKProperties,GatewayCenterService gatewayCenterService){ return new GatewaySDKApplication(gatewaySDKProperties,gatewayCenterService); } }
2301_82000044/my-api-gateway
my-api-gateway-sdk/src/main/java/zack/gateway/sdk/config/GatewaySDKAutoConfig.java
Java
mit
1,204
package zack.gateway.sdk.config; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @author A1793 */ @ConfigurationProperties("api-gateway-sdk") public class GatewaySDKProperties { private String enable; private String address; private String systemId; private String systemName; private String systemRegistry; public String getEnable() { return enable; } public void setEnable(String enable) { this.enable = enable; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public String getSystemName() { return systemName; } public void setSystemName(String systemName) { this.systemName = systemName; } public String getSystemRegistry() { return systemRegistry; } public void setSystemRegistry(String systemRegistry) { this.systemRegistry = systemRegistry; } }
2301_82000044/my-api-gateway
my-api-gateway-sdk/src/main/java/zack/gateway/sdk/config/GatewaySDKProperties.java
Java
mit
1,168
package zack.gateway.sdk.domain.service; import cn.hutool.http.HttpUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import zack.gateway.sdk.GatewayException; import zack.gateway.sdk.common.Result; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * @author A1793 */ public class GatewayCenterService { private Logger logger = LoggerFactory.getLogger(GatewayCenterService.class); public void doRegisterApplication(String address, String systemId, String systemName, String systemType, String systemRegistry) { Map<String, Object> parameters = new HashMap<>(); parameters.put("systemId", systemId); parameters.put("systemName", systemName); parameters.put("systemType", systemType); parameters.put("systemRegistry", systemRegistry); String resultStr = null; try { resultStr = HttpUtil.post(address + "/wg/admin/register/registerApplication", parameters, 55000); } catch (Exception e) { logger.error("应用服务注册异常,链接资源不可用:{}", address + "/wg/admin/register/registerApplication"); throw e; } Result<Boolean> result = JSON.parseObject(resultStr, new TypeReference<Result<Boolean>>() { }); logger.info("向网关中心注册应用服务 systemId:{} systemName:{} 注册结果:{}", systemId, systemName, resultStr); if (!"0000".equals(result.getCode()) && !"0003".equals(result.getCode())) { throw new GatewayException("注册应用服务异常 [systemId:" + systemId + "] 、[systemRegistry:" + systemRegistry + "]"); } } public void doRegisterApplicationInterface(String address, String systemId, String interfaceId, String interfaceName, String interfaceVersion) { Map<String, Object> parameters = new HashMap<>(); parameters.put("systemId", systemId); parameters.put("interfaceId", interfaceId); parameters.put("interfaceName", interfaceName); parameters.put("interfaceVersion", interfaceVersion); String resultStr = null; try { resultStr = HttpUtil.post(address + "/wg/admin/register/registerApplicationInterface", parameters, 55000); } catch (Exception e) { logger.error("应用服务接口注册异常,链接资源不可用:{}", address + "/wg/admin/register/registerApplicationInterface"); throw e; } Result<Boolean> result = JSON.parseObject(resultStr, new TypeReference<Result<Boolean>>() { }); if (!"0000".equals(result.getCode()) && !"0003".equals(result.getCode())) { throw new GatewayException("向网关中心注册应用接口服务异常 [systemId:" + systemId + "] 、[interfaceId:" + interfaceId + "]"); } } public void doRegisterApplicationInterfaceMethod(String address, String systemId, String interfaceId, String methodId, String methodName, String parameterType, String uri, String httpCommandType, Integer auth) { Map<String, Object> parameters = new HashMap<>(); parameters.put("systemId", systemId); parameters.put("interfaceId", interfaceId); parameters.put("methodId", methodId); parameters.put("methodName", methodName); parameters.put("parameterType", parameterType); parameters.put("uri", uri); parameters.put("httpCommandType", httpCommandType); parameters.put("auth", auth); String resultStr = null; try { resultStr = HttpUtil.post(address + "/wg/admin/register/registerApplicationInterfaceMethod", parameters, 55000); } catch (Exception e) { logger.error("应用服务接口注册方法异常,链接资源不可用:{}", address + "/wg/admin/register/registerApplicationInterfaceMethod"); throw e; } Result<Boolean> result = JSON.parseObject(resultStr, new TypeReference<Result<Boolean>>() { }); if (!"0000".equals(result.getCode()) && !"0003".equals(result.getCode())) { throw new GatewayException("向网关中心注册应用接口方法服务异常 [systemId:" + systemId + "] 、[interfaceId:" + interfaceId + "]、[methodId:]" + methodId + "]"); } } public void doRegisterEvent(String address,String systemId){ Map<String, Object> paramMap = new HashMap<>(); paramMap.put("systemId", systemId); String resultStr; try { resultStr = HttpUtil.post(address + "/wg/admin/register/registerEvent", paramMap, 55000); } catch (Exception e) { logger.error("应用服务接口事件方法异常,链接资源不可用:{}", address + "/wg/admin/register/registerEvent"); throw e; } Result<Boolean> result = JSON.parseObject(resultStr, new TypeReference<Result<Boolean>>() { }); logger.info("应用服务接口事件方法 systemId:{} 注册结果:{}", systemId, resultStr); if (!"0000".equals(result.getCode())) { throw new GatewayException("向网关中心注册应用接口服务异常 [systemId:" + systemId + "] "); } } }
2301_82000044/my-api-gateway
my-api-gateway-sdk/src/main/java/zack/gateway/sdk/domain/service/GatewayCenterService.java
Java
mit
5,735
# 基础镜像 FROM openjdk:8-jre-slim # 作者 MAINTAINER zackzky # 配置 ENV PARAMS="" # 时区 ENV TZ=PRC RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 添加应用 ADD /target/my-api-gateway-test.jar /my-api-gateway-test.jar ## 在镜像运行为容器后执行的命令 ENTRYPOINT ["sh","-c","java -jar $JAVA_OPTS /my-api-gateway-test.jar $PARAMS"]
2301_82000044/my-api-gateway
my-api-gateway-test/Dockerfile
Dockerfile
mit
389
docker build -f ./Dockerfile -t zackzky/my-api-gateway-test:1.6 .
2301_82000044/my-api-gateway
my-api-gateway-test/build.sh
Shell
mit
65
#!/bin/bash # https://cr.console.aliyun.com/cn-hangzhou/instance/credentials # Ensure the script exits if any command fails set -e # Define variables for the registry and image ALIYUN_REGISTRY="crpi-f2fnckn7fe4gfuf0.cn-hangzhou.personal.cr.aliyuncs.com" NAMESPACE="zackzky" IMAGE_NAME="my-api-gateway-test" IMAGE_TAG="1.1" # 读取本地配置文件 if [ -f ".local-config" ]; then source .local-config else echo ".local-config 文件不存在,请创建并填写 ALIYUN_USERNAME 和 ALIYUN_PASSWORD" exit 1 fi # Login to Aliyun Docker Registry echo "Logging into Aliyun Docker Registry..." docker login --username="${ALIYUN_USERNAME}" --password="${ALIYUN_PASSWORD}" $ALIYUN_REGISTRY # Tag the Docker image echo "Tagging the Docker image..." docker tag ${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG} ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG} # Push the Docker image to Aliyun echo "Pushing the Docker image to Aliyun..." docker push ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG} echo "Docker image pushed successfully! " echo "检出地址:docker pull ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}" echo "标签设置:docker tag ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG} ${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}" # Logout from Aliyun Docker Registry echo "Logging out from Aliyun Docker Registry..." docker logout $ALIYUN_REGISTRY
2301_82000044/my-api-gateway
my-api-gateway-test/push.sh
Shell
mit
1,405
package zack.gateway; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @Configurable @EnableDubbo public class RpcApplication { public static void main(String[] args) { SpringApplication.run(RpcApplication.class, args); } }
2301_82000044/my-api-gateway
my-api-gateway-test/src/main/java/zack/gateway/RpcApplication.java
Java
mit
474
package zack.gateway.interfaces; import com.alibaba.fastjson.JSON; import org.apache.dubbo.config.annotation.Service; import zack.gateway.rpc.IActivityBooth; import zack.gateway.rpc.dto.XReq; import zack.gateway.sdk.annotations.ApiProducerClazz; import zack.gateway.sdk.annotations.ApiProducerMethod; @Service(version = "1.0.0") @ApiProducerClazz(interfaceName = "活动服务", interfaceVersion = "1.0.0") public class ActivityBooth implements IActivityBooth { @Override @ApiProducerMethod(methodName = "探活方法", uri = "/wg/activity/sayHi", httpCommandType = "GET", auth = 0) public String sayHi(String str) { return "hi " + str + " by api-gateway-test-provider"; } @Override @ApiProducerMethod(methodName = "插入方法", uri = "/wg/activity/insert", httpCommandType = "POST", auth = 1) public String insert(XReq req) { return "hi " + JSON.toJSONString(req) + " by api-gateway-test-provider"; } @Override @ApiProducerMethod(methodName = "测试方法", uri = "/wg/activity/test", httpCommandType = "POST", auth = 0) public String test(String str, XReq req) { return "hi " + str + JSON.toJSONString(req) + " by api-gateway-test-provider"; } }
2301_82000044/my-api-gateway
my-api-gateway-test/src/main/java/zack/gateway/interfaces/ActivityBooth.java
Java
mit
1,231
package zack.gateway.rpc; import zack.gateway.rpc.dto.XReq; public interface IActivityBooth { String sayHi(String str); String insert(XReq req); String test(String str, XReq req); }
2301_82000044/my-api-gateway
my-api-gateway-test/src/main/java/zack/gateway/rpc/IActivityBooth.java
Java
mit
200
package zack.gateway.rpc.dto; public class XReq { private String uid; private String name; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
2301_82000044/my-api-gateway
my-api-gateway-test/src/main/java/zack/gateway/rpc/dto/XReq.java
Java
mit
357