# Conflicts: # sop-example/sop-story/src/main/resources/application-dev.properties # sop-gateway/pom.xml # sop-website/sop-website-server/pom.xmleureka
commit
726e35116c
@ -0,0 +1,54 @@ |
||||
package com.gitee.sop.gatewaycommon.gateway.controller; |
||||
|
||||
import com.gitee.sop.gatewaycommon.bean.SpringContext; |
||||
import com.gitee.sop.gatewaycommon.gateway.loadbalancer.SopLoadBalancerClient; |
||||
import org.springframework.cloud.client.ServiceInstance; |
||||
import org.springframework.cloud.gateway.webflux.ProxyExchange; |
||||
import org.springframework.http.ResponseEntity; |
||||
import org.springframework.stereotype.Controller; |
||||
import org.springframework.util.StringUtils; |
||||
import org.springframework.web.bind.annotation.RequestMapping; |
||||
import org.springframework.web.server.ServerWebExchange; |
||||
import reactor.core.publisher.Mono; |
||||
|
||||
/** |
||||
* 处理restful请求 |
||||
* @author tanghc |
||||
*/ |
||||
@Controller |
||||
public class RestfulController { |
||||
|
||||
private static final int PREFIX_LEN = "/rest/".length(); |
||||
|
||||
@RequestMapping("/rest/**") |
||||
public Mono<ResponseEntity<byte[]>> proxy(ProxyExchange<byte[]> proxy, ServerWebExchange exchange) { |
||||
String path = proxy.path(); |
||||
String serviceId = getServiceId(path); |
||||
String targetPath = getTargetPath(serviceId, path); |
||||
String rawQuery = exchange.getRequest().getURI().getRawQuery(); |
||||
if (StringUtils.hasLength(rawQuery)) { |
||||
targetPath = targetPath + "?" + rawQuery; |
||||
} |
||||
// 负载均衡
|
||||
ServiceInstance serviceInstance = SpringContext.getBean(SopLoadBalancerClient.class).choose(serviceId, exchange); |
||||
String uri = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + targetPath; |
||||
return proxy.uri(uri).forward(); |
||||
} |
||||
|
||||
/** |
||||
* 从path中解析出serviceId |
||||
* @param path 格式:/rest/<serviceId><real_path> |
||||
* @return 返回serviceId |
||||
*/ |
||||
private String getServiceId(String path) { |
||||
path = path.substring(PREFIX_LEN); |
||||
int index = path.indexOf('/'); |
||||
path = path.substring(0, index); |
||||
return path; |
||||
} |
||||
|
||||
private String getTargetPath(String serviceId, String path) { |
||||
int len = PREFIX_LEN + serviceId.length(); |
||||
return path.substring(len); |
||||
} |
||||
} |
@ -1,6 +1,10 @@ |
||||
server.port=2222 |
||||
spring.application.name=story-service |
||||
register.url=http://localhost:1111/eureka/ |
||||
# 注册中心 |
||||
# \u6CE8\u518C\u4E2D\u5FC3 |
||||
eureka.client.serviceUrl.defaultZone=${register.url} |
||||
|
||||
|
||||
# \u4E0A\u4F20\u6587\u4EF6\u6700\u5927\u503C |
||||
spring.servlet.multipart.max-file-size=20MB |
||||
spring.servlet.multipart.max-request-size=20MB |
Loading…
Reference in new issue