一個簡單輕量的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

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