Ribbon注解方式有哪些

Ribbon是微服务的一个核心基础组件,提供多协议HTTP、TCP以及UDP的服务调用RPC功能以及负载均衡功能。

Ribbon:一个客户端IPC(Inter Process Communication)库,RPC(Remote Procedure Calls)库。支持负载均衡、故障容错、多协议支持:HTTP, TCP, UDP,支持异步(asynchronous)以及reactive模型、Caching 以及batching。

举例某个api应用,运行了两个实例(部署了2台机器),这个应用提供了两个api:

1、/test

2、/test/{version}

这两个api都有个参数data,/test/{version}还有个@PathVariable的version参数。

/test定义如下:

Java代码  
@ResponseBody  
@RequestMapping(value = "test")  
public String test(@RequestParam String data) {  
    return data;  
}  
/test/{version}定义如下:

Java代码
@ResponseBody  
@RequestMapping(value = "test/{version}")  
public String testvn(@PathVariable String version, @RequestParam String data) {  
    return data + ";version=" + version;  
}  
就是两个普通的api,和我们以前写的api是一样的,可以直接请求:

http://localhost:8081/test?data=aaa

http://localhost:8082/test?data=aaa

http://localhost:8081/test/1.0?data=aaa

http://localhost:8082/test/1.0?data=aaa

通过ribbon调用这俩个api服务:

注解方式:

Java代码
public interface TestService {  
  
    @Http(  
            method = Http.HttpMethod.GET,  
            uri = "/test?data={data}"  
    )  
    RibbonRequest<ByteBuf> test(@Var("data") String data);  
  
    @Http(  
            method = Http.HttpMethod.GET,  
            uri = "/test/{version}?data={data}"  
    )  
    RibbonRequest<ByteBuf> testvn(@Var("version") String version, @Var("data") String data);  
}  
通过ribbon调用/test服务:

Java代码

@Test
public void test11() {  
    ConfigurationManager.getConfigInstance().setProperty("TestService.ribbon." + CommonClientConfigKey.MaxAutoRetriesNextServer, "3");  
    ConfigurationManager.getConfigInstance().setProperty("TestService.ribbon." + CommonClientConfigKey.ListOfServers, "localhost:8082,localhost:8081");  
  
    TestService testService = Ribbon.from(TestService.class);  
    RibbonRequest<ByteBuf> request = testService.test("aaa");  
  
    ByteBuf result0 = request.execute();  
    ByteBuffer buf = result0.nioBuffer();  
    byte[] bytes = new byte[buf.remaining()];  
    buf.get(bytes);  
    System.out.println(new String(bytes));  
}  
通过ribbon调用/test/{version}服务:

Java代码  

@Test
public void test21() {  
    ConfigurationManager.getConfigInstance().setProperty("TestService.ribbon." + CommonClientConfigKey.MaxAutoRetriesNextServer, "3");  
    ConfigurationManager.getConfigInstance().setProperty("TestService.ribbon." + CommonClientConfigKey.ListOfServers, "localhost:8082,localhost:8081");  
  
    TestService testService = Ribbon.from(TestService.class);  
    RibbonRequest<ByteBuf> request = testService.testvn("1.0", "aaa");  
  
    ByteBuf result0 = request.execute();  
    ByteBuffer buf = result0.nioBuffer();  
    byte[] bytes = new byte[buf.remaining()];  
    buf.get(bytes);  
    System.out.println(new String(bytes));  
}  

猜你喜欢

转载自blog.csdn.net/lyc00net/article/details/87357507
今日推荐