在分布式模式下,微服务的跨服务调用,需要在每个服务中实现controller层,比较麻烦,最好可以把service层的方法直接映射到controller。
有个叫leecho的大佬捣鼓出一个叫spring-cloud-feign-proxy的微服务动态代理框架,可惜3年多没更新了,目前的springboot版本已经没法用了,更何况最新的springboot3版本了。
下面分享一个我日常使用的方法,不受springcloud版本限制,比较灵活。
java版本:17
springboot版本:2.6.2
springcloud版本:2021.0.0
以一个小型分布式系统为例,看下代理模块的结构
先定义2个注解
/**
*
* @author 万剑魔君
* 定义需要提供服务的类
*/
@Documented
@Target(value = { ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface FeignProxy {
String value() default "";
//是否自动扫描类中的方法
boolean autoScan() default true;
}
/**
*
* @author 万剑魔君
* 定义方法上的请求路径
*/
@Documented
@Target(value = { ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface ProxyPath {
String value() default "";
//开启自动扫描时,是否忽略该方法
boolean ignore() default false;
}
增加一个组件,用于获取spirng上下文
@Component
public class SpringContext implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
public Object getBean(String name) {
return getApplicationContext().getBean(name);