【能力上架申请】添加api网关集成

This commit is contained in:
huangweixiong 2022-05-09 15:30:52 +08:00
parent c994be67d2
commit fd0a070abc
8 changed files with 150 additions and 22 deletions

View File

@ -7,7 +7,7 @@ import org.springframework.stereotype.Component;
@Data @Data
@Component @Component
@PropertySource("classpath:/yaweisso.properties") @PropertySource("classpath:yaweisso.properties")
@ConfigurationProperties(prefix = "sso") @ConfigurationProperties(prefix = "sso")
public class YaweiSSOProperties { public class YaweiSSOProperties {
private String domain; private String domain;

View File

@ -66,4 +66,9 @@ public class TAbilityApplicationEntity {
* 用户id * 用户id
*/ */
private String userId; private String userId;
/**
* 流程通过后api网关注册的认证code用于三方接口调用
*/
private String gatewayCode;
} }

View File

@ -1,9 +1,12 @@
package io.renren.modules.processForm.listener; package io.renren.modules.processForm.listener;
import cn.hutool.core.lang.UUID;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import io.renren.modules.processForm.dto.TAbilityApplicationDTO; import io.renren.modules.processForm.dto.TAbilityApplicationDTO;
import io.renren.modules.processForm.service.ApiGatewayService;
import io.renren.modules.resource.dto.ResourceDTO; import io.renren.modules.resource.dto.ResourceDTO;
import io.renren.modules.resource.entity.ResourceEntity;
import io.renren.modules.resource.service.ResourceService; import io.renren.modules.resource.service.ResourceService;
import io.renren.modules.sys.dto.SysDeptDTO; import io.renren.modules.sys.dto.SysDeptDTO;
import io.renren.modules.sys.dto.SysRoleDTO; import io.renren.modules.sys.dto.SysRoleDTO;
@ -12,6 +15,8 @@ import io.renren.modules.sys.service.SysDeptService;
import io.renren.modules.sys.service.SysRoleService; import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysRoleUserService; import io.renren.modules.sys.service.SysRoleUserService;
import io.renren.modules.sys.service.SysUserService; import io.renren.modules.sys.service.SysUserService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService; import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.*; import org.activiti.engine.delegate.*;
import org.activiti.engine.delegate.event.ActivitiEvent; import org.activiti.engine.delegate.event.ActivitiEvent;
@ -47,6 +52,9 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti
@Autowired @Autowired
private SysDeptService sysDeptService; private SysDeptService sysDeptService;
@Autowired
private ApiGatewayService apiGatewayService;
@Autowired @Autowired
private ResourceService resourceService; private ResourceService resourceService;
@ -58,6 +66,9 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti
case EVENTNAME_CREATE: case EVENTNAME_CREATE:
create(delegateTask); create(delegateTask);
break; break;
case EVENTNAME_COMPLETE:
complete(delegateTask);
break;
default: default:
} }
logger.error("-------------------------结束部门动态审批人流程-------------------------------"); logger.error("-------------------------结束部门动态审批人流程-------------------------------");
@ -138,4 +149,31 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti
taskService.setAssignee(delegateTask.getId(), "1516728698224427010"); taskService.setAssignee(delegateTask.getId(), "1516728698224427010");
} }
} }
/**
* 审批通过申请code
* @param delegateTask
*/
private void complete(DelegateTask delegateTask) {
Map<String, Object> kv = delegateTask.getVariables();
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(kv);
TAbilityApplicationDTO abilityApplicationDTO = gson.fromJson(jsonElement, TAbilityApplicationDTO.class);
ResourceEntity resourceEntity = resourceService.selectById(abilityApplicationDTO.getResourceId());
//没有groupid当做没有接口直接跳过
if (resourceEntity.getGroupId() == null)
return;
String code = UUID.randomUUID().toString();
apiGatewayService.subscribeCode(String.valueOf(abilityApplicationDTO.getId()), code);
delegateTask.setVariable("gatewayCode", code);
String apiPrefix = "/juapi/" + abilityApplicationDTO.getResourceId();
TaskService taskService = ProcessEngines.getDefaultProcessEngine().getTaskService();
String msg = String.format("您的能力申请已通过接口认证code为%s, 接口公共前缀为:%s",code, apiPrefix) ;
taskService.addComment(delegateTask.getId(), delegateTask.getProcessInstanceId(), msg);
}
} }

View File

@ -1,9 +1,14 @@
package io.renren.modules.processForm.service; package io.renren.modules.processForm.service;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.renren.modules.processForm.dao.TAbilityApplicationDao;
import io.renren.modules.processForm.entity.TAbilityApplicationEntity;
import io.renren.modules.resource.dao.ResourceDao; import io.renren.modules.resource.dao.ResourceDao;
import io.renren.modules.resource.entity.ResourceEntity; import io.renren.modules.resource.entity.ResourceEntity;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -21,40 +26,60 @@ import java.util.regex.Pattern;
@Service @Service
@Slf4j @Slf4j
/**
* 聚好看网关对接相关
*
*/
public class ApiGatewayService { public class ApiGatewayService {
@Autowired @Autowired
private ResourceDao resourceDao; private ResourceDao resourceDao;
@Autowired
private TAbilityApplicationDao abilityApplicationDao;
@Autowired @Autowired
private RestTemplate restTemplate; private RestTemplate restTemplate;
@Value("${hisense.gateway.url:http://devtest-security-app.hismarttv.com:8080}") @Value("${hisense.gateway.url}")
private String gatewayUrl; private String gatewayUrl;
/** /** 将api注册到网关
* 注册流程创建group -> 创建路由(api)并关联到group下未来可多个api关联
* @param resourceId 能力资源的id * @param resourceId 能力资源的id
* @return * @return
*/ */
public void registerApi2Gateway(String resourceId){ public void registerApi2Gateway(String resourceId){
if (resourceId == null) { if (resourceId == null) {
log.warn("传入resourceId为空"); throw new IllegalArgumentException("传入resourceId为空");
return;
} }
ResourceEntity resourceEntity = resourceDao.selectById(resourceId); ResourceEntity resourceEntity = resourceDao.selectById(resourceId);
if (resourceEntity == null) {
throw new IllegalArgumentException(String.format("未找到对应的资源id:%s", resourceId));
}
String apiUrl = resourceEntity.getApiUrl(); String apiUrl = resourceEntity.getApiUrl();
String methods = resourceEntity.getApiMethodType().toUpperCase();
if (apiUrl == null || !apiUrl.startsWith("http")){ if (StringUtils.isBlank(apiUrl) || StringUtils.isBlank(methods)){
log.warn("非法apiurl apiUrl:{} resourceId:{}",apiUrl, resourceId); String msg = String.format("注册api参数为空跳过 apiUrl:%s, methods:%s, resourceId:%s", apiUrl, methods, resourceId);
//重要参数没有当成不需要注册
log.info(msg);
return; return;
} }
//建group //建group
String domain = getIP(apiUrl); String domain = getIP(apiUrl);
String uris = apiUrl.substring(apiUrl.indexOf(domain) + domain.length());
if (StringUtils.isBlank(uris)) {
uris = "/";
}
String apiPrefix = "/juapi/" + resourceId;
HashMap groupEntity = new HashMap(); HashMap groupEntity = new HashMap();
groupEntity.put("id", resourceId);
groupEntity.put("name", resourceEntity.getName()); groupEntity.put("name", resourceEntity.getName());
groupEntity.put("stripPrefixPattern",String.format("^%s/(.*)", apiPrefix));
groupEntity.put("serviceName",domain ); groupEntity.put("serviceName",domain );
String groupUrl = gatewayUrl + "/apiops/api/groups"; String groupUrl = gatewayUrl + "/apiops/api/groups";
@ -63,17 +88,17 @@ public class ApiGatewayService {
HashMap body = responseEntity.getBody(); HashMap body = responseEntity.getBody();
String id = (String) body.get("id"); String id = (String) body.get("id");
if (StringUtils.isBlank(id)){ if (StringUtils.isBlank(id)){
log.error("创建group时id为空 {} body:{}", JSON.toJSONString(groupEntity), body); String error = String.format("创建group时id为空 request:%s body:%s", JSON.toJSONString(groupEntity), body);
return; throw new RuntimeException(error);
} }
//建路由接口url //建路由接口url
String routeUrl = gatewayUrl + "apiops/api/routers"; String routeUrl = gatewayUrl + "/apiops/api/routers";
HashMap routeEntity = new HashMap(); HashMap routeEntity = new HashMap();
routeEntity.put("name", "api:1:" + resourceEntity.getName()); routeEntity.put("name", "api:1:" + resourceEntity.getName());
routeEntity.put("group", id); routeEntity.put("group", id);
routeEntity.put("methods", resourceEntity.getApiMethodType().toUpperCase()); routeEntity.put("methods", methods);
routeEntity.put("uris", apiUrl.substring(apiUrl.indexOf(domain) + domain.length())); routeEntity.put("uris", apiPrefix + uris);
ResponseEntity<HashMap> routeResEntity = restTemplate.postForEntity(routeUrl, routeEntity, HashMap.class); ResponseEntity<HashMap> routeResEntity = restTemplate.postForEntity(routeUrl, routeEntity, HashMap.class);
if (routeResEntity.getStatusCode() != HttpStatus.OK || !responseEntity.hasBody()){ if (routeResEntity.getStatusCode() != HttpStatus.OK || !responseEntity.hasBody()){
//失败则删除group //失败则删除group
@ -89,6 +114,55 @@ public class ApiGatewayService {
} }
} }
/**
* 将code关联到groupapi这希望code由我们来生成
* 关联流程创建消费者 -> 订阅接口传入code关联消费者与group
* @param formId
* @param code
*/
public void subscribeCode( String formId, String code){
if ( StringUtils.isBlank(formId) || StringUtils.isBlank(code)) {
throw new IllegalArgumentException(String.format("关键参数不能为空 formId:%s code:%s", formId, code));
}
TAbilityApplicationEntity applicationEntity = abilityApplicationDao.selectById(formId);
ResourceEntity resourceEntity = resourceDao.selectById(applicationEntity.getResourceId());
String groupId = resourceEntity.getGroupId();
if (resourceEntity == null){
throw new RuntimeException(String.format("找不到资源类 groupId:%s", groupId));
}
//注册消费者一个表单关联一个消费者
HashMap consumerEntity = new HashMap();
consumerEntity.put("id", formId);
consumerEntity.put("name", resourceEntity.getName() + "-concumer");
String consumerUrl = gatewayUrl + "/apiops/api/consumers";
HashMap consumerResponse = restTemplate.postForEntity(consumerUrl, consumerEntity, HashMap.class).getBody();
if (consumerResponse == null || !formId.equals(consumerResponse.get("id"))){
throw new RuntimeException(String.format("消费者创建失败 response: %s", consumerResponse));
}
//订阅
HashMap subscribeEntity = new HashMap();
subscribeEntity.put("consumerId", formId);
subscribeEntity.put("routerId", groupId);
subscribeEntity.put("routerType","group");
subscribeEntity.put("code", code);
String subscribeUrl = gatewayUrl + "/apiops/api/subscribers";
HashMap body = restTemplate.postForEntity(subscribeUrl, subscribeEntity, HashMap.class).getBody();
if (body == null || StringUtils.isBlank((String) body.get("consumerId"))){
throw new RuntimeException(String.format("订阅失败 response: %s", body));
}
LambdaUpdateWrapper<TAbilityApplicationEntity> updateWrapper = new UpdateWrapper<TAbilityApplicationEntity>().lambda()
.eq(TAbilityApplicationEntity::getId, formId)
.set(TAbilityApplicationEntity::getGatewayCode, code);
abilityApplicationDao.update(null, updateWrapper);
}
private String getIP(String url) { private String getIP(String url) {
String re = "((http|ftp|https)://)(([a-zA-Z0-9._-]+)|([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}))(([a-zA-Z]{2,6})|(:[0-9]{1,4})?)"; String re = "((http|ftp|https)://)(([a-zA-Z0-9._-]+)|([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}))(([a-zA-Z]{2,6})|(:[0-9]{1,4})?)";
String str = ""; String str = "";

View File

@ -79,9 +79,9 @@ public class ResourceOwnerListener implements TaskListener, ExecutionListener, A
case EVENTNAME_CREATE: // 创建当前审批节点事件 case EVENTNAME_CREATE: // 创建当前审批节点事件
create(delegateTask, roleDTO); create(delegateTask, roleDTO);
break; break;
// case EVENTNAME_COMPLETE: case EVENTNAME_COMPLETE:
// complete(delegateTask); complete(delegateTask);
// break; break;
default: default:
logger.error("未处理该事件:" + eventName); logger.error("未处理该事件:" + eventName);
} }
@ -124,7 +124,7 @@ public class ResourceOwnerListener implements TaskListener, ExecutionListener, A
} }
/** /**
* 流程结束推送 * 流程结束接口推送api
* *
* @param delegateTask * @param delegateTask
*/ */
@ -134,7 +134,7 @@ public class ResourceOwnerListener implements TaskListener, ExecutionListener, A
JsonElement jsonElement = gson.toJsonTree(kv); JsonElement jsonElement = gson.toJsonTree(kv);
TResourceMountApplyDTO resourceMountApplyDTO = gson.fromJson(jsonElement, TResourceMountApplyDTO.class); TResourceMountApplyDTO resourceMountApplyDTO = gson.fromJson(jsonElement, TResourceMountApplyDTO.class);
Long resourceID = resourceMountApplyDTO.getResourceDTO().getId(); Long resourceID = resourceMountApplyDTO.getResourceDTO().getId();
// apiGatewayService.registerApi2Gateway(String.valueOf(resourceID)); apiGatewayService.registerApi2Gateway(String.valueOf(resourceID));
ResourceDTO re = resourceMountApplyDTO.getResourceDTO(); ResourceDTO re = resourceMountApplyDTO.getResourceDTO();
if (re != null) { if (re != null) {

View File

@ -43,3 +43,7 @@ resource:
big_date: big_date:
name: 青岛市大数据发展管理局 name: 青岛市大数据发展管理局
assignee_role_name: 部门审批人 assignee_role_name: 部门审批人
hisense:
gateway:
url: http://devtest-security-app.hismarttv.com:8080

View File

@ -1,3 +1,3 @@
sso.domain=yw.com.cn sso.domain=127.0.0.1:8080
sso.ssoKey=SSOToken sso.ssoKey=SSOToken
sso.keeperUrl=http://127.0.0.1:9090/renren-admin/sys/user/123 sso.keeperUrl=http://jhoa.qd.gov.cn

View File

@ -1,5 +1,6 @@
package io.renren; package io.renren;
import cn.hutool.core.lang.UUID;
import io.renren.common.redis.RedisUtils; import io.renren.common.redis.RedisUtils;
import io.renren.modules.processForm.service.ApiGatewayService; import io.renren.modules.processForm.service.ApiGatewayService;
import io.renren.modules.sys.entity.SysUserEntity; import io.renren.modules.sys.entity.SysUserEntity;
@ -17,8 +18,14 @@ public class ApiGatewayServiceTest {
private ApiGatewayService apiGatewayService; private ApiGatewayService apiGatewayService;
@Test @Test
public void contextLoads() { public void registerApi2Gateway() {
apiGatewayService.registerApi2Gateway("1519505145602723841"); apiGatewayService.registerApi2Gateway("1522550194523152385");
}
@Test
public void registerCode2Group() {
String code = UUID.randomUUID().toString();
apiGatewayService.subscribeCode("1522550733273112577", code);
} }
} }