云脑群网关接入

This commit is contained in:
lizhicheng 2022-09-07 13:46:14 +08:00
parent 2349aec38e
commit 2a453b02d8
11 changed files with 281 additions and 40 deletions

View File

@ -7,7 +7,7 @@ import com.google.gson.JsonElement;
import io.renren.common.annotation.ActivitiNoticeOperation;
import io.renren.modules.activiti.service.ActTaskService;
import io.renren.modules.processForm.dto.TAbilityApplicationDTO;
import io.renren.modules.processForm.service.ApiGatewayService;
import io.renren.modules.processForm.service.ApiGateway;
import io.renren.modules.processForm.service.TAbilityApplicationService;
import io.renren.modules.resource.dto.ResourceDTO;
import io.renren.modules.resource.entity.ResourceEntity;
@ -33,6 +33,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
@ -62,8 +63,8 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti
private SysRoleUserService sysRoleUserService;
@Autowired
private SysDeptService sysDeptService;
@Autowired
private ApiGatewayService apiGatewayService;
@Resource(name = "${hisense.gateway.name}")
private ApiGateway apiGateway;
@Autowired
private ResourceService resourceService;
@ -273,7 +274,7 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti
return;
}
String code = UUID.randomUUID().toString();
apiGatewayService.subscribeCode(String.valueOf(abilityApplicationDTO.getId()), code);
apiGateway.subscribeCode(String.valueOf(abilityApplicationDTO.getId()), code);
delegateTask.setVariable("gatewayCode", code);

View File

@ -9,7 +9,7 @@ import io.renren.common.annotation.ActivitiNoticeOperation;
import io.renren.common.dto.AuditingBaseDTO;
import io.renren.modules.activiti.service.ActTaskService;
import io.renren.modules.processForm.dto.TAbilityApplicationDTO;
import io.renren.modules.processForm.service.ApiGatewayService;
import io.renren.modules.processForm.service.ApiGateway;
import io.renren.modules.processForm.service.TAbilityApplicationService;
import io.renren.modules.resource.dto.ResourceDTO;
import io.renren.modules.resource.entity.ResourceEntity;
@ -35,6 +35,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
@ -62,8 +63,8 @@ public class CorrectionListenerV2 implements TaskListener, ExecutionListener, Ac
private SysRoleUserService sysRoleUserService;
@Autowired
private SysDeptService sysDeptService;
@Autowired
private ApiGatewayService apiGatewayService;
@Resource(name = "${hisense.gateway.name}")
private ApiGateway apiGateway;
@Autowired
private ResourceService resourceService;
@ -279,7 +280,7 @@ public class CorrectionListenerV2 implements TaskListener, ExecutionListener, Ac
return;
String code = UUID.randomUUID().toString();
apiGatewayService.subscribeCode(String.valueOf(abilityApplicationDTO.getId()), code);
apiGateway.subscribeCode(String.valueOf(abilityApplicationDTO.getId()), code);
delegateTask.setVariable("gatewayCode", code);
@ -312,7 +313,7 @@ public class CorrectionListenerV2 implements TaskListener, ExecutionListener, Ac
hasData = true;
String code = UUID.randomUUID().toString();
apiGatewayService.subscribeCode(String.valueOf(abilityApplicationDTO.getId()), code);
apiGateway.subscribeCode(String.valueOf(abilityApplicationDTO.getId()), code);
String apiPrefix = "/juapi/" + abilityApplicationDTO.getResourceId();
String msg = String.format("能力名称:%s接口认证code为%s, 接口公共前缀为:%s", resourceEntity.getName(), code, apiPrefix);
allMsg.append(msg);

View File

@ -9,7 +9,7 @@ import io.renren.common.annotation.ActivitiNoticeOperation;
import io.renren.common.dto.AuditingBaseDTO;
import io.renren.modules.activiti.service.ActTaskService;
import io.renren.modules.processForm.dto.TAbilityApplicationDTO;
import io.renren.modules.processForm.service.ApiGatewayService;
import io.renren.modules.processForm.service.ApiGateway;
import io.renren.modules.processForm.service.TAbilityApplicationService;
import io.renren.modules.resource.dto.ResourceDTO;
import io.renren.modules.resource.entity.ResourceEntity;
@ -37,6 +37,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
@ -65,8 +66,8 @@ public class CorrectionListenerV3 implements TaskListener, ExecutionListener, Ac
private SysRoleUserService sysRoleUserService;
@Autowired
private SysDeptService sysDeptService;
@Autowired
private ApiGatewayService apiGatewayService;
@Resource(name = "${hisense.gateway.name}")
private ApiGateway apiGateway;
@Autowired
private ResourceService resourceService;
@ -292,7 +293,7 @@ public class CorrectionListenerV3 implements TaskListener, ExecutionListener, Ac
return;
String code = UUID.randomUUID().toString();
apiGatewayService.subscribeCode(String.valueOf(abilityApplicationDTO.getId()), code);
apiGateway.subscribeCode(String.valueOf(abilityApplicationDTO.getId()), code);
delegateTask.setVariable("gatewayCode", code);
@ -325,7 +326,7 @@ public class CorrectionListenerV3 implements TaskListener, ExecutionListener, Ac
hasData = true;
String code = UUID.randomUUID().toString();
apiGatewayService.subscribeCode(String.valueOf(abilityApplicationDTO.getId()), code);
apiGateway.subscribeCode(String.valueOf(abilityApplicationDTO.getId()), code);
String apiPrefix = "/juapi/" + abilityApplicationDTO.getResourceId();
String msg = String.format("能力名称:%s接口认证code为%s, 接口公共前缀为:%s", resourceEntity.getName(), code, apiPrefix);
allMsg.append(msg);

View File

@ -0,0 +1,16 @@
package io.renren.modules.processForm.service;
/**
* @Auther:lizhicheng2@hisense.com
* @date:2022/9/5
* @des
*/
public interface ApiGateway {
void subscribeCode( String formId, String code);
void registerApi2Gateway(String resourceId);
void resetApiGroup(String groupId);
}

View File

@ -0,0 +1,222 @@
package io.renren.modules.processForm.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Sets;
import io.renren.modules.processForm.dao.TAbilityApplicationDao;
import io.renren.modules.processForm.entity.TAbilityApplicationEntity;
import io.renren.modules.processForm.service.ApiGateway;
import io.renren.modules.resource.dao.ResourceDao;
import io.renren.modules.resource.entity.AttrEntity;
import io.renren.modules.resource.entity.ResourceEntity;
import io.renren.modules.resource.service.ResourceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Auther:lizhicheng2@hisense.com
* @date:2022/9/5
* @des
*/
@Service("云脑群网关")
@Slf4j
public class HibrianApiGateway implements ApiGateway {
@Autowired
private ResourceDao resourceDao;
@Autowired
private ResourceService resourceService;
@Autowired
private TAbilityApplicationDao abilityApplicationDao;
@Autowired
private RestTemplate restTemplate;
@Value("${hisense.gateway.url}")
private String gatewayUrl;
private static final String API_PREFIX = "/apiops/api";
@Override
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 serviceId = resourceEntity.getGroupId();
if (resourceEntity == null) {
throw new RuntimeException(String.format("找不到资源类 serviceId:%s", serviceId));
}
//注册消费者一个表单关联一个消费者
HashMap consumerEntity = new HashMap();
//consumerEntity.put("id", formId);
consumerEntity.put("username", formId);
consumerEntity.put("key", code);
String consumerUrl = gatewayUrl + API_PREFIX + "/v1/consumers";
restTemplate.put(consumerUrl, consumerEntity, HashMap.class);
// 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("resourceId", serviceId);
subscribeEntity.put("resourceType", "service");
String subscribeUrl = gatewayUrl + API_PREFIX + "/subscribers";
HashMap body = restTemplate.postForEntity(subscribeUrl, subscribeEntity, HashMap.class).getBody();
if (body == null || HttpStatus.OK.value() != Integer.parseInt(body.get("code").toString())) {
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);
}
@Override
public void registerApi2Gateway(String resourceId) {
if (resourceId == null) {
throw new IllegalArgumentException("传入resourceId为空");
}
ResourceEntity resourceEntity = resourceDao.selectById(resourceId);
if (resourceEntity == null) {
throw new IllegalArgumentException(String.format("未找到对应的资源id:%s", resourceId));
}
String apiUrl = "";
Optional<AttrEntity> optional = resourceService.selectAttrsByResourceId(Long.parseLong(resourceId)).stream().filter(attr -> attr.getAttrType().equals("服务接口")).findFirst();
if (optional.isPresent()) {
apiUrl = optional.get().getAttrValue();
}
String methods = "";
if (resourceEntity.getApiMethodType() != null) {
methods = resourceEntity.getApiMethodType().toUpperCase();
}
Long deptId = resourceEntity.getDeptId();
HashSet supportMethod = Sets.newHashSet("POST", "GET");
if (StringUtils.isBlank(apiUrl) || deptId == null || deptId == 0 || StringUtils.isBlank(methods) || !supportMethod.contains(methods)) {
String msg = String.format("注册api参数为空跳过 apiUrl:%s, deptId:%ld methods:%s, resourceId:%s", apiUrl, deptId, methods, resourceId);
//重要参数没有当成不需要注册
log.info(msg);
return;
}
//创建service
String domain = getIP(apiUrl);
String uris = apiUrl.substring(apiUrl.indexOf(domain) + domain.length());
if (StringUtils.isBlank(uris)) {
uris = "/";
}
String apiPrefix = "/hibrianapi/" + deptId + "/" + resourceId;
HashMap serviceEntity = new HashMap();
serviceEntity.put("id", resourceId);
serviceEntity.put("name", resourceEntity.getName());
serviceEntity.put("stripPrefixPattern", String.format("^%s/(.*)", apiPrefix));
serviceEntity.put("nodes", domain);
String serviceUrl = gatewayUrl + API_PREFIX + "/v1/services";
ResponseEntity<HashMap> responseEntity = restTemplate.postForEntity(serviceUrl, serviceEntity, HashMap.class);
if (responseEntity.getStatusCode() == HttpStatus.OK && responseEntity.hasBody()) {
HashMap body = responseEntity.getBody();
if (HttpStatus.OK.value() == Integer.parseInt(body.get("code").toString())) {
Map data = (Map) body.get("data");
String id = data.get("id").toString();
if (StringUtils.isBlank(id)) {
String error = String.format("创建group时id为空 request:%s body:%s", JSON.toJSONString(serviceEntity), data);
throw new RuntimeException(error);
}
//建路由接口url
String routeUrl = gatewayUrl + API_PREFIX + "/v1/routes";
HashMap routeEntity = new HashMap();
routeEntity.put("name", "api:1:" + resourceEntity.getName());
routeEntity.put("service_id", id);
routeEntity.put("methods", methods);
routeEntity.put("uris", apiPrefix + uris);
routeEntity.put("enableMetric", true);
ResponseEntity<HashMap> routeResEntity = restTemplate.postForEntity(routeUrl, routeEntity, HashMap.class);
if (routeResEntity.getStatusCode() != HttpStatus.OK || !responseEntity.hasBody() || HttpStatus.OK.value() != Integer.parseInt(routeResEntity.getBody().get("code").toString())) {
//失败则删除group
restTemplate.delete(serviceUrl + "/" + id);
} else {
resourceEntity.setGroupId(id);
LambdaUpdateWrapper<ResourceEntity> updateWrapper = new UpdateWrapper<ResourceEntity>().lambda();
updateWrapper.eq(ResourceEntity::getId, resourceEntity.getId());
updateWrapper.set(ResourceEntity::getGroupId, id);
resourceDao.update(null, updateWrapper);
}
}
}
}
@Override
public void resetApiGroup(String serviceId) {
String apiQueryUrl = gatewayUrl + API_PREFIX + "/v1/routes/filter?serviceId=" + serviceId;
ResponseEntity<HashMap> forEntity = restTemplate.getForEntity(apiQueryUrl, HashMap.class);
HashMap body = forEntity.getBody();
if (!body.isEmpty()) {
List<Map> content = (List<Map>) body.get("data");
for (Map map : content) {
String id = (String) ((Map) map.get("value")).get("id");
if (StringUtils.isNotBlank(id)) {
String apiDelUrl = gatewayUrl + API_PREFIX + "/v1/routes/" + id;
try {
restTemplate.delete(apiDelUrl);
} catch (Exception e) {
}
}
}
deleteGroup(serviceId);
}
}
public void deleteGroup(String serviceId) {
String serviceUrl = gatewayUrl + API_PREFIX + "/v1/services";
restTemplate.delete(serviceUrl + "/" + serviceId);
}
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 str = "";
Pattern pattern = Pattern.compile(re);
Matcher matcher = pattern.matcher(url);
if (matcher.matches()) {
str = url;
} else {
String[] split2 = url.split(re);
if (split2.length > 1) {
String substring = url.substring(0, url.length() - split2[1].length());
str = substring;
} else {
str = split2[0];
}
}
int lastIndexOf = str.lastIndexOf("/");
return str.substring(lastIndexOf + 1);
}
}

View File

@ -1,4 +1,4 @@
package io.renren.modules.processForm.service;
package io.renren.modules.processForm.service.impl;
import cn.hutool.core.lang.UUID;
@ -10,6 +10,7 @@ import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Sets;
import io.renren.modules.processForm.dao.TAbilityApplicationDao;
import io.renren.modules.processForm.entity.TAbilityApplicationEntity;
import io.renren.modules.processForm.service.ApiGateway;
import io.renren.modules.resource.dao.ResourceDao;
import io.renren.modules.resource.entity.ResourceEntity;
import lombok.extern.slf4j.Slf4j;
@ -25,13 +26,13 @@ import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
@Service("聚好看网关")
@Slf4j
/**
* 聚好看网关对接相关
*
*/
public class ApiGatewayService {
public class JuApiGateway implements ApiGateway {
@Autowired
private ResourceDao resourceDao;

View File

@ -10,7 +10,7 @@ import io.renren.common.utils.Result;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.modules.processForm.service.ApiGatewayService;
import io.renren.modules.processForm.service.ApiGateway;
import io.renren.modules.resource.dataResource.AbstractDataResourceService;
import io.renren.modules.resource.dataResource.DataResourceFactory;
import io.renren.modules.resource.dto.GetDataResourceListDto;
@ -39,6 +39,7 @@ import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@ -108,8 +109,8 @@ public class ResourceController {
@Autowired
private SysDeptService sysDeptService;
@Autowired
private ApiGatewayService apiGatewayService;
@Resource(name = "${hisense.gateway.name}")
private ApiGateway apiGateway;
@Lazy
@Autowired
@ -274,7 +275,7 @@ public class ResourceController {
if (!"f".equals(source) && dto.getId() != null) {//后台挂架直接上架
try {
apiGatewayService.registerApi2Gateway(dto.getId().toString());
apiGateway.registerApi2Gateway(dto.getId().toString());
} catch (Exception exception) {
//注册失败忽略简单记录一下
logger.error("挂接网关注册失败", exception);
@ -288,8 +289,8 @@ public class ResourceController {
@PostMapping("/registerApi2Gateway")
public Result registerApi2Gateway(@RequestParam String source) {
try {
apiGatewayService.resetApiGroup(source);
apiGatewayService.registerApi2Gateway(source);
apiGateway.resetApiGroup(source);
apiGateway.registerApi2Gateway(source);
} catch (Exception exception) {
//注册失败忽略简单记录一下
logger.error("挂接网关注册失败", exception);

View File

@ -8,7 +8,7 @@ import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import io.renren.common.annotation.ActivitiNoticeOperation;
import io.renren.modules.activiti.service.ActTaskService;
import io.renren.modules.processForm.service.ApiGatewayService;
import io.renren.modules.processForm.service.ApiGateway;
import io.renren.modules.resource.dto.ResourceDTO;
import io.renren.modules.resource.entity.ResourceEntityDelFlag;
import io.renren.modules.resource.service.ResourceService;
@ -30,6 +30,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
@ -53,8 +54,8 @@ public class ResourceOwnerListener implements TaskListener, ExecutionListener, A
private TaskService taskService;
@Autowired
private SysUserService sysUserService;
@Autowired
private ApiGatewayService apiGatewayService;
@Resource(name = "${hisense.gateway.name}")
private ApiGateway apiGateway;
@Autowired
private SysDeptService sysDeptService;
@Autowired
@ -149,7 +150,7 @@ public class ResourceOwnerListener implements TaskListener, ExecutionListener, A
resourceService.update(re);
logger.error("审批通过资源id:" + re.getId());
try {
apiGatewayService.registerApi2Gateway(String.valueOf(re.getId())); // 发布到应用网关
apiGateway.registerApi2Gateway(String.valueOf(re.getId())); // 发布到应用网关
} catch (Exception exception) {
logger.error("发布到应用网关", exception);
}

View File

@ -77,6 +77,7 @@ big_date:
hisense:
gateway:
name: 聚好看网关
url: http://devtest-security-app.hismarttv.com:8080
qdyjj:

View File

@ -3,26 +3,23 @@ package io.renren;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.redis.RedisUtils;
import io.renren.modules.processForm.service.ApiGatewayService;
import io.renren.modules.processForm.service.ApiGateway;
import io.renren.modules.resource.dao.ResourceDao;
import io.renren.modules.resource.entity.ResourceEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApiGatewayServiceTest {
@Autowired
private ApiGatewayService apiGatewayService;
@Resource(name = "${hisense.gateway.name}")
private ApiGateway apiGateway;
@Autowired
private ResourceDao resourceDao;
@ -42,8 +39,8 @@ public class ApiGatewayServiceTest {
List<ResourceEntity> resourceEntities = resourceDao.selectList(select);
resourceEntities.forEach(item -> {
String id = String.valueOf(item.getId());
apiGatewayService.resetApiGroup(id);
apiGatewayService.registerApi2Gateway(id);
apiGateway.resetApiGroup(id);
apiGateway.registerApi2Gateway(id);
});
}
@ -51,15 +48,15 @@ public class ApiGatewayServiceTest {
@Test
public void registerAPI(){
String id = "1522550194544123907";
apiGatewayService.resetApiGroup(id);
apiGateway.resetApiGroup(id);
apiGatewayService.registerApi2Gateway(id);
apiGateway.registerApi2Gateway(id);
}
@Test
public void registerCode2Group() {
String code = UUID.randomUUID().toString();
apiGatewayService.subscribeCode("1522756586483789825", code);
apiGateway.subscribeCode("1522756586483789825", code);
System.out.println(code);
}

View File

@ -4,7 +4,6 @@ import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.modules.gateway.service.MonitorServiceV2;
import io.renren.modules.processForm.service.ApiGatewayService;
import io.renren.modules.resource.dao.ResourceDao;
import io.renren.modules.resource.entity.ResourceEntity;
import org.junit.Test;