一个简单轻量的rpc框架,不使用任何注册中心实现远程调用。

spring-cloud-invoker-parent

介绍

目前只支持 spring boot 2.0 + 版本

一个简单轻量的rpc框架,不使用任何注册中心。
目前spring-cloud-starter-invoker使用http方式引用htppInvoker模块实现service暴露,从而实现远程调用功能。
并基于eureka、nacos基本原理,获取注册中心“服务模块”IP地址。同时也支持项目中,没有注册中心场景下的项目。

更新说明

1、 2.0.0 开启spring boot 2.0 + 版本支持

2、 2.0.1 主要新增实例,整理invoker代码,修改2.0.0遗留bug。新增支持oauth2验证

application.yml 配置

http:
  invoker:
    connectionRequestTimeout: 15000
    connectTimeout: 20000
    readTimeout: 15000
    maxQueueSize: 1000
  remote:
    enabled: false

maven

  1. pom.xml 添加如下代码
    
    <dependency>
        <groupId>com.sample</groupId>
        <artifactId>spring-cloud-starter-invoker</artifactId>
        <version>${project.version}</version>
    </dependency>

     

使用说明1、 启动类


@SpringBootApplication
@EnableDiscoveryClient
@EnableRemoteClients
@ComponentScan(basePackages={"com.xxx"})
public class TestBootstrap {

    public static void main(String[] args) {
        final ConfigurableApplicationContext run = SpringApplication.run(TestBootstrap.class);
    }
}

2、 暴露service


@RemoteService
public class TestService implements TestServiceFacade {
   public String test(){
	return "ok";
   }
}

3、 添加接口与熔断,并指向模块调用注册中心地址进行远程访问

3.1) 有注册中心下使用,如果没有项目名(projectPath)则为空或不填写
@RemoteClient(name = "cx-test",fallback = TestServiceFacadeHystrix.class, projectPath = "/projectName")
public interface TestServiceFacade {
   public String test();
}

public class TestServiceFacadeHystrix implements TestServiceFacade{
   public String test(){
	return "ok";
   }
}
3.2) 非注册中心下使用,如果没有项目名(projectPath)则为空或不填写
@RemoteClient(address = "127.0.0.1:8080",fallback = TestServiceFacadeHystrix.class, projectPath = "/projectName")
public interface TestServiceFacade {
   public String test();
}

public class TestServiceFacadeHystrix implements TestServiceFacade{
   public String test(){
	return "ok";
   }
}

4、 客服端使用接口


@RestController
@RequestMapping("/test")
public class ChatController {

    @Autowired
    private TestServiceFacade testServiceFacade;


    @RequestMapping("/test")
    public String test(){
        return testServiceFacade.test();
    }
}

5、oauth2 服务调用验证

@Component
public class RequestInterceptor implements HttpInvokerRequestInterceptor {
	@Override
	public void apply(RequestTemplate requestTemplate) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if ((authentication instanceof AbstractAuthenticationToken)) {
			AbstractAuthenticationToken aat = (AbstractAuthenticationToken)authentication;
			if ((aat.getDetails() instanceof OAuth2AuthenticationDetails)) {
				OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)aat.getDetails();
                requestTemplate.addHeaders("Authorization", new String(String.format("%s %s", new Object[] { details.getTokenType(), details.getTokenValue() })));
			}
		}
	}
}

 

git地址:https://gitee.com/liju023/spring-cloud-invoker-parent

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章