12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- package com.yiidata.dataops.server.config;
- import com.yiidata.dataops.server.modules.gateway.entity.OpsGatewayServer;
- import com.yiidata.dataops.server.modules.gateway.service.OpsGatewayServerService;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.lang.StringUtils;
- import org.springframework.beans.factory.InitializingBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.autoconfigure.web.ServerProperties;
- import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator;
- import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import java.util.List;
- import java.util.Map;
- import java.util.Optional;
- import java.util.stream.Collectors;
- /**
- * <pre>
- *
- * Created by zhenqin.
- * User: zhenqin
- * Date: 2022/4/25
- * Time: 下午7:08
- * Vendor: yiidata.com
- *
- * </pre>
- *
- * @author zhenqin
- */
- @Slf4j
- @Configuration
- public class ApiGatewayConfig implements InitializingBean {
- @Autowired
- OpsGatewayServerService opsGatewayServerService;
- @Autowired
- ServerProperties serverProperties;
- @Autowired
- ZuulProperties zuulProperties;
- @Override
- public void afterPropertiesSet() throws Exception {
- final List<OpsGatewayServer> gatewayServers = opsGatewayServerService.list();
- final Map<String, List<OpsGatewayServer>> listMap = gatewayServers.stream()
- .collect(Collectors.groupingBy(OpsGatewayServer::getApiRouter));
- for (Map.Entry<String, List<OpsGatewayServer>> entry : listMap.entrySet()) {
- if(entry.getValue() == null || entry.getValue().isEmpty()) {
- continue;
- }
- // 代理地址
- String url = entry.getValue().stream()
- .map(OpsGatewayServer::getApiUrl)
- .map(StringUtils::trimToNull)
- .filter(StringUtils::isNotBlank)
- .collect(Collectors.joining(","));
- // 代理路由
- String path = Optional.ofNullable(StringUtils.trimToNull(entry.getValue().get(0).getApiPath())).orElse("/" + entry.getKey() + "/**");
- final ZuulProperties.ZuulRoute route = new ZuulProperties.ZuulRoute();
- route.setId(entry.getKey());
- route.setPath(path);
- route.setUrl(url);
- log.info("add router {} to path: {}", path, url);
- zuulProperties.getRoutes().putIfAbsent(entry.getKey(), route);
- }
- // 初始化
- zuulProperties.init();
- }
- /**
- * 支持简单的负载均衡
- * @return
- */
- @Bean
- public SimpleRouteLocator simpleRouteLocator() {
- return new ApiRouteLocator(this.serverProperties.getServlet().getContextPath(),
- this.zuulProperties);
- }
- }
|