适配eureka

This commit is contained in:
tanghc
2019-09-27 20:06:52 +08:00
parent be0adc0a8e
commit 35253be77d
40 changed files with 751 additions and 294 deletions

View File

@@ -1,7 +1,5 @@
package com.gitee.sop.adminserver.api.service;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.naming.NamingService;
import com.gitee.easyopen.annotation.Api;
import com.gitee.easyopen.annotation.ApiService;
import com.gitee.easyopen.doc.annotation.ApiDoc;
@@ -27,6 +25,7 @@ import com.gitee.sop.adminserver.entity.ConfigGray;
import com.gitee.sop.adminserver.entity.ConfigGrayInstance;
import com.gitee.sop.adminserver.mapper.ConfigGrayInstanceMapper;
import com.gitee.sop.adminserver.mapper.ConfigGrayMapper;
import com.gitee.sop.adminserver.mapper.ConfigServiceRouteMapper;
import com.gitee.sop.adminserver.service.ConfigPushService;
import com.gitee.sop.adminserver.service.RegistryService;
import lombok.extern.slf4j.Slf4j;
@@ -60,59 +59,37 @@ public class ServiceApi {
@Autowired
private ConfigGrayInstanceMapper configGrayInstanceMapper;
@Autowired
private ConfigServiceRouteMapper configServiceRouteMapper;
@Autowired
private ConfigPushService configPushService;
@NacosInjected
private NamingService namingService;
@Api(name = "registry.service.list")
@ApiDocMethod(description = "注册中心的服务列表", elementClass = RouteServiceInfo.class)
List<RouteServiceInfo> listServiceInfo(ServiceSearchParam param) {
List<ServiceInfo> servicesOfServer = null;
try {
servicesOfServer = registryService.listAllService(1, Integer.MAX_VALUE);
} catch (Exception e) {
log.error("获取服务列表失败", e);
throw new BizException("获取服务列表失败");
}
return servicesOfServer
@ApiDocMethod(description = "路由配置中的服务列表", elementClass = String.class)
List<String> listServiceInfo(ServiceSearchParam param) {
List<String> allServiceId = configServiceRouteMapper.listAllServiceId();
return allServiceId
.stream()
.filter(serviceInfo -> {
String serviceId = serviceInfo.getServiceId();
if ("api-gateway".equalsIgnoreCase(serviceId)) {
return false;
}
// 隐藏空服务
if (CollectionUtils.isEmpty(serviceInfo.getInstances())) {
return false;
}
.filter(serviceId -> {
if (StringUtils.isBlank(param.getServiceId())) {
return true;
} else {
return serviceId.contains(param.getServiceId());
}
})
.map(serviceInfo -> {
RouteServiceInfo routeServiceInfo = new RouteServiceInfo();
routeServiceInfo.setServiceId(serviceInfo.getServiceId());
return routeServiceInfo;
})
.collect(Collectors.toList());
}
@Api(name = "service.custom.add")
@ApiDocMethod(description = "添加服务")
void addService(ServiceAddParam param) {
// TODO: 添加服务
throw new BizException("该功能已下线");
}
@Api(name = "service.custom.del")
@ApiDocMethod(description = "删除自定义服务")
void delService(ServiceSearchParam param) {
// TODO: 删除自定义服务
throw new BizException("该功能已下线");
}

View File

@@ -10,11 +10,13 @@ import com.gitee.easyopen.interceptor.ApiInterceptor;
import com.gitee.easyopen.session.ApiSessionManager;
import com.gitee.sop.adminserver.interceptor.LoginInterceptor;
import com.gitee.sop.adminserver.service.RegistryService;
import com.gitee.sop.adminserver.service.impl.RegistryServiceEurekaImpl;
import com.gitee.sop.adminserver.service.impl.RegistryServiceNacosImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@@ -75,10 +77,22 @@ public class WebConfig {
* @return
*/
@Bean
@ConditionalOnProperty(value = "registry.name", havingValue = "nacos", matchIfMissing = true)
RegistryService registryServiceNacos() {
return new RegistryServiceNacosImpl();
}
/**
* 当配置了registry.name=eureka生效。
*
* @return
*/
@Bean
@ConditionalOnProperty(value = "registry.name", havingValue = "eureka")
RegistryService registryServiceEureka() {
return new RegistryServiceEurekaImpl();
}
@PostConstruct
public void after() {
}

View File

@@ -2,10 +2,17 @@ package com.gitee.sop.adminserver.mapper;
import com.gitee.fastmybatis.core.mapper.CrudMapper;
import com.gitee.sop.adminserver.entity.ConfigServiceRoute;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* @author tanghc
*/
public interface ConfigServiceRouteMapper extends CrudMapper<ConfigServiceRoute, Long> {
@Select("SELECT distinct service_id FROM config_service_route")
List<String> listAllServiceId();
}

View File

@@ -0,0 +1,14 @@
package com.gitee.sop.adminserver.service.impl;
import lombok.Data;
import java.util.List;
/**
* @author tanghc
*/
@Data
public class EurekaApplication {
private String name;
private List<EurekaInstance> instance;
}

View File

@@ -0,0 +1,13 @@
package com.gitee.sop.adminserver.service.impl;
import lombok.Data;
import java.util.List;
/**
* @author tanghc
*/
@Data
public class EurekaApplications {
private List<EurekaApplication> application;
}

View File

@@ -0,0 +1,11 @@
package com.gitee.sop.adminserver.service.impl;
import lombok.Data;
/**
* @author tanghc
*/
@Data
public class EurekaApps {
private EurekaApplications applications;
}

View File

@@ -0,0 +1,70 @@
package com.gitee.sop.adminserver.service.impl;
import lombok.Data;
import org.springframework.util.CollectionUtils;
import java.util.Map;
/**
* {
* "instance": {
* "instanceId": "demo-order2:11101",
* "app": "demo-order2",
* "appGroutName": null,
* "ipAddr": "127.0.0.1",
* "sid": "na",
* "homePageUrl": null,
* "statusPageUrl": null,
* "healthCheckUrl": null,
* "secureHealthCheckUrl": null,
* "vipAddress": "demo-order2",
* "secureVipAddress": "demo-order2",
* "countryId": 1,
* "dataCenterInfo": {
* "@class": "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo",
* "name": "MyOwn"
* },
* "hostName": "127.0.0.1",
* "status": "UP",
* "leaseInfo": null,
* "isCoordinatingDiscoveryServer": false,
* "lastUpdatedTimestamp": 1529391461000,
* "lastDirtyTimestamp": 1529391461000,
* "actionType": null,
* "asgName": null,
* "overridden_status": "UNKNOWN",
* "port": {
* "$": 11102,
* "@enabled": "false"
* },
* "securePort": {
* "$": 7002,
* "@enabled": "false"
* },
* "metadata": {
* "@class": "java.util.Collections$EmptyMap"
* }* }
* }
* @author tanghc
*/
@Data
public class EurekaInstance {
private String instanceId;
private String ipAddr;
private Map<String, Object> port;
private String status;
private String statusPageUrl;
private String healthCheckUrl;
private String lastUpdatedTimestamp;
private Map<String, String> metadata;
public String fetchPort() {
if (CollectionUtils.isEmpty(port)) {
return "";
}
return String.valueOf(port.getOrDefault("$", ""));
}
}

View File

@@ -0,0 +1,84 @@
package com.gitee.sop.adminserver.service.impl;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.internal.http.HttpMethod;
/**
* https://github.com/Netflix/eureka/wiki/Eureka-REST-operations
*
* @author tanghc
*/
public enum EurekaUri {
/**
* 查询所有实例 Query for all instances
*/
QUERY_APPS("GET", "/apps"),
/**
* 查询一个实例
*/
QUERY_INSTANCES("GET", "/instances/%s"),
/**
* 下线 Take instance out of service
*/
OFFLINE_SERVICE("PUT", "/apps/%s/%s/status?value=OUT_OF_SERVICE"),
/**
* 上线 Move instance back into service (remove override)
*/
ONLINE_SERVICE("DELETE", "/apps/%s/%s/status?value=UP"),
/**
* 设置metadata信息
*
* /apps/{appID}/{instanceID}/metadata?key=value
*/
SET_METADATA("PUT", "/apps/%s/%s/metadata?%s=%s")
;
public static final String URL_PREFIX = "/";
String uri;
String requestMethod;
EurekaUri(String httpMethod, String uri) {
if (!uri.startsWith(URL_PREFIX)) {
uri = "/" + uri;
}
this.uri = uri;
this.requestMethod = httpMethod;
}
public String getUri(String... args) {
if (args == null || args.length == 0) {
return uri;
}
Object[] param = new Object[args.length];
for (int i = 0; i < args.length; i++) {
param[i] = args[i];
}
return String.format(uri, param);
}
public Request getRequest(String url, String... args) {
if (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
String requestUrl = url + getUri(args);
Request request = this.getBuilder()
.url(requestUrl)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
return request;
}
public Request.Builder getBuilder() {
String method = requestMethod;
RequestBody requestBody = null;
if (HttpMethod.requiresRequestBody(method)) {
MediaType contentType = MediaType.parse("application/json");
requestBody = RequestBody.create(contentType, "{}");
}
return new Request.Builder().method(requestMethod, requestBody);
}
}

View File

@@ -0,0 +1,94 @@
package com.gitee.sop.adminserver.service.impl;
import com.alibaba.fastjson.JSON;
import com.gitee.sop.adminserver.bean.ServiceInfo;
import com.gitee.sop.adminserver.bean.ServiceInstance;
import com.gitee.sop.adminserver.service.RegistryService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* eureka接口实现
* @author tanghc
*/
@Slf4j
public class RegistryServiceEurekaImpl implements RegistryService {
private OkHttpClient client = new OkHttpClient();
@Value("${eureka.client.serviceUrl.defaultZone:}")
private String eurekaUrl;
@Override
public List<ServiceInfo> listAllService(int pageNo, int pageSize) throws Exception {
if (StringUtils.isBlank(eurekaUrl)) {
throw new IllegalArgumentException("未指定eureka.client.serviceUrl.defaultZone参数");
}
String json = this.requestEurekaServer(EurekaUri.QUERY_APPS);
EurekaApps eurekaApps = JSON.parseObject(json, EurekaApps.class);
List<ServiceInfo> serviceInfoList = new ArrayList<>();
List<EurekaApplication> applicationList = eurekaApps.getApplications().getApplication();
for (EurekaApplication eurekaApplication : applicationList) {
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setServiceId(eurekaApplication.getName());
List<EurekaInstance> instanceList = eurekaApplication.getInstance();
if (!CollectionUtils.isEmpty(instanceList)) {
serviceInfo.setInstances(new ArrayList<>(instanceList.size()));
for (EurekaInstance eurekaInstance : instanceList) {
ServiceInstance serviceInstance = new ServiceInstance();
serviceInstance.setInstanceId(eurekaInstance.getInstanceId());
serviceInstance.setServiceId(serviceInfo.getServiceId());
serviceInstance.setIp(eurekaInstance.getIpAddr());
serviceInstance.setPort(Integer.valueOf(eurekaInstance.fetchPort()));
serviceInstance.setStatus(eurekaInstance.getStatus());
Date updateTime = new Date(Long.valueOf(eurekaInstance.getLastUpdatedTimestamp()));
serviceInstance.setUpdateTime(DateFormatUtils.format(updateTime, TIMESTAMP_PATTERN));
serviceInstance.setMetadata(eurekaInstance.getMetadata());
serviceInfo.getInstances().add(serviceInstance);
}
}
serviceInfoList.add(serviceInfo);
}
return serviceInfoList;
}
@Override
public void onlineInstance(ServiceInstance serviceInstance) throws Exception {
this.requestEurekaServer(EurekaUri.ONLINE_SERVICE, serviceInstance.getServiceId(), serviceInstance.getInstanceId());
}
@Override
public void offlineInstance(ServiceInstance serviceInstance) throws Exception {
this.requestEurekaServer(EurekaUri.OFFLINE_SERVICE, serviceInstance.getServiceId(), serviceInstance.getInstanceId());
}
@Override
public void setMetadata(ServiceInstance serviceInstance, String key, String value) throws Exception {
this.requestEurekaServer(EurekaUri.SET_METADATA, serviceInstance.getServiceId(), serviceInstance.getInstanceId(), key, value);
}
private String requestEurekaServer(EurekaUri eurekaUri, String... args) throws IOException {
Request request = eurekaUri.getRequest(this.eurekaUrl, args);
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
log.error("操作失败url:{}, msg:{}, code:{}", eurekaUri.getUri(args), response.message(), response.code());
throw new RuntimeException("操作失败");
}
}
}

View File

@@ -11,10 +11,16 @@ mysql.password=root
nacos.url=127.0.0.1:8848
# 网关地址,多个用逗号隔开
# 此配置仅在使用eureka时有用不用的话注释掉
# 在不使用nacos时有用使用nacos时注释掉
gateway.host=127.0.0.1:8081
# ------- 需要改的配置end -------
# eureka注册中心
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
# 如果使用eureka填eureka使用nacos填eureka
registry.name=eureka
# token过期时间分钟
admin.access-token.timeout-minutes=30
# 签名方式rsa支付宝开放平台签名方式md5淘宝开放平台签名方式

View File

@@ -382,14 +382,13 @@ export default {
convertToTreeData(data, pid) {
const result = []
const root = {
label: '服务列表',
label: data.length === 0 ? '无服务' : '服务列表',
parentId: pid
}
const children = []
for (let i = 0; i < data.length; i++) {
data[i].parentId = 1
data[i].label = data[i].serviceId
children.push(data[i])
const child = { parentId: 1, label: data[i] }
children.push(child)
}
root.children = children
result.push(root)

View File

@@ -52,7 +52,8 @@
size="mini"
icon="el-icon-delete"
title="删除服务"
@click.stop="() => onDelService(data)"/>
@click.stop="() => onDelService(data)"
/>
</span>
</span>
</el-tree>
@@ -60,7 +61,10 @@
<el-main style="padding-top:0">
<el-form :inline="true" :model="searchFormData" class="demo-form-inline" size="mini">
<el-form-item label="路由名称">
<el-input v-model="searchFormData.id" placeholder="输入接口名或版本号" />
<el-input v-model="searchFormData.id" :clearable="true" placeholder="输入接口名或版本号" />
</el-form-item>
<el-form-item>
<el-checkbox v-model="searchFormData.permission">授权接口</el-checkbox>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="el-icon-search" @click="onSearchTable">查询</el-button>
@@ -76,9 +80,9 @@
新建路由
</el-button>
<el-table
:data="tableData"
:data="pageInfo.rows"
border
max-height="500"
highlight-current-row
style="margin-top: 10px;"
>
<el-table-column
@@ -141,6 +145,17 @@
</template>
</el-table-column>
</el-table>
<el-pagination
background
style="margin-top: 5px"
:current-page="searchFormData.pageIndex"
:page-size="searchFormData.pageSize"
:page-sizes="[10, 20, 40]"
:total="pageInfo.total"
layout="total, sizes, prev, pager, next"
@size-change="onSizeChange"
@current-change="onPageIndexChange"
/>
</el-main>
</el-container>
<!-- route dialog -->
@@ -252,7 +267,14 @@ export default {
isCustomService: false,
searchFormData: {
id: '',
serviceId: ''
serviceId: '',
permission: 0,
pageIndex: 1,
pageSize: 10
},
pageInfo: {
rows: [],
total: 0
},
defaultProps: {
children: 'children',
@@ -347,37 +369,36 @@ export default {
/**
* 数组转成树状结构
* @param data 数据结构 [{
"_parentId": 14,
"gmtCreate": "2019-01-15 09:44:38",
"gmtUpdate": "2019-01-15 09:44:38",
"id": 15,
"isShow": 1,
"name": "用户注册",
"orderIndex": 10000,
"parentId": 14
},...]
"_parentId": 14,
"gmtCreate": "2019-01-15 09:44:38",
"gmtUpdate": "2019-01-15 09:44:38",
"id": 15,
"isShow": 1,
"name": "用户注册",
"orderIndex": 10000,
"parentId": 14
},...]
* @param pid 初始父节点id一般是0
* @return 返回结果 [{
label: '一级 1',
label: '一级 1',
children: [{
label: '二级 1-1',
children: [{
label: '级 1-1',
children: [{
label: '三级 1-1-1'
}]
label: '级 1-1-1'
}]
}
}]
}
*/
convertToTreeData(data, pid) {
const result = []
const root = {
label: '服务列表',
label: data.length === 0 ? '无服务' : '服务列表',
parentId: pid
}
const children = []
for (let i = 0; i < data.length; i++) {
data[i].parentId = 1
data[i].label = data[i].serviceId
children.push(data[i])
const child = { parentId: 1, label: data[i] }
children.push(child)
}
root.children = children
result.push(root)
@@ -385,12 +406,17 @@ export default {
},
// table
loadTable: function(param) {
if (!this.searchFormData.serviceId) {
this.tip('请选择一个服务', 'error')
return
}
const postData = param || this.searchFormData
this.post('route.list', postData, function(resp) {
this.tableData = resp.data
this.post('route.page', postData, function(resp) {
this.pageInfo = resp.data
})
},
onSearchTable: function() {
this.searchFormData.pageIndex = 1
this.loadTable()
},
onTableUpdate: function(row) {
@@ -509,6 +535,14 @@ export default {
this.loadTree()
})
})
},
onSizeChange: function(size) {
this.searchFormData.pageSize = size
this.loadTable()
},
onPageIndexChange: function(pageIndex) {
this.searchFormData.pageIndex = pageIndex
this.loadTable()
}
}
}