场景
切换空间时访问的都是pkm-system命名空间的同一个服务aia-portal-svc的同一个接口,接口参数是命名空间名字。接口拿参数namespace和服务所在空间的环境变量My_POD_NAMESPACE比较,相同则调用自身服务,不同则通过Feign根据参数namespace动态生成URL,调用别的空间的服务接口。
AiaPortalAdminFeignClient
- @FeignClient注解的configuration属性值配置为自定义的AiaPortalAdminFeignClientRequestInterceptor.class,AiaPortalAdminFeignClientRequestInterceptor.class是实现动态URL的关键。
- url = "${plm.service.urls.aia-portal-svc:aia-portal-svc.plm-system:4000}",配置了默认的URL为aia-portal-svc.plm-system:4000,经测试url属性不能去掉,否则虽然AiaPortalAdminFeignClientRequestInterceptor.class动态生成的URL是对的,但是RPC客户端在远程调用时会报错:
- FeignClient中GET请求方式被强制转换为POST方式,解决方式:参数添加@RequestParam(value = "namespace")。从今天FeignClient中GET方式被强制转换为POST方式说起 - 简书
import com.genertech.plm.aia.portaladmin.entity.Site;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* @author: huo.qw
* @createTime: 2024/07/26 上午 11:35
* @description:
*/
@FeignClient(name = "aiaPortalAdminFeignClient", path = "", url = "${plm.service.urls.aia-portal-svc:aia-portal-svc:4000}"
, configuration = AiaPortalAdminFeignClientRequestInterceptor.class)
public interface AiaPortalAdminFeignClient {
@GetMapping("/user/getUserSiteByNamespace")
public List<Site> getUserSiteByNamespace(@RequestParam(value = "namespace") String namespace);
}
AiaPortalAdminFeignClientRequestInterceptor
- 不要加@Component,否则所有的FeignClient都会使用此配置,仅在AiaPortalAdminFeignClient中的@FeignClient添加配置即可。
- 也不需要添加额外的配置类。
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
/**
* @author: huo.qw
* @createTime: 2024/07/26 下午 01:44
* @description:
*/
@Slf4j
//不要加@Component,否则所有的FeignClient都会使用此配置,仅在AiaPortalAdminFeignClient中的@FeignClient添加配置即可
public class AiaPortalAdminFeignClientRequestInterceptor implements RequestInterceptor {
@Resource
Environment environment;
private final static String HOST = "http://aia-portal-svc.";
private final static String PORT = ":4000";
@Override
public void apply(RequestTemplate requestTemplate) {
String namespace = null;
try {
// 从请求中获取get参数namespace
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
namespace = servletRequestAttributes.getRequest().getParameter("namespace");
log.info("namespace: {}", namespace);
} catch (Exception e) {
log.info("namespace 获取异常");
e.printStackTrace();
}
if (StringUtils.isEmpty(namespace)) {
namespace = environment.getProperty("MY_POD_NAMESPACE");
}
String url = HOST + namespace + PORT;
log.info("AiaPortalAdminFeignClientRequestInterceptor target url: {}", url);
requestTemplate.target(url);
}
}