|
| 1 | +# 分布式服务框架之Dubbo(隐式参数) |
| 2 | + |
| 3 | +### 隐式参数 |
| 4 | +通过 Dubbo 中的 Attachment 在服务消费方和提供方之间隐式传递参数。 |
| 5 | +注意:path, group, version, dubbo, token, timeout 几个 key 是保留字段,请使用其它值。 |
| 6 | + |
| 7 | +<img src="https://ipman-blog-1304583208.cos.ap-nanjing.myqcloud.com/dubbo/1031608635201_.pic_hd.jpg" width = "620" height = "160" alt="图片名称" align=center /> |
| 8 | + |
| 9 | +### Dubbo隐式参数实战 |
| 10 | +##### 1.客户端通过setAttachment设置隐式参数,在完成下面一次远程调用会被清空,即多次远程调用要多次设置 |
| 11 | +```java |
| 12 | +public class AttachmentConsumer { |
| 13 | + |
| 14 | + public static void main(String[] args) { |
| 15 | + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/attachment-consumer.xml"); |
| 16 | + AttachmentService attachmentService = context.getBean("attachmentService", AttachmentService.class); |
| 17 | + // 隐式传参,后面的远程调用都会隐式将这些参数发送到服务器端,类似cookie |
| 18 | + RpcContext.getContext().setAttachment("index", "1"); |
| 19 | + |
| 20 | + // 业务,远程调用 |
| 21 | + // Hello ipman, response from provider: 10.13.224.253:20880, attachment - index: 1 |
| 22 | + System.out.println(attachmentService.sayHello("ipman")); |
| 23 | + } |
| 24 | +} |
| 25 | +``` |
| 26 | + |
| 27 | +##### 2.服务端通过getAttachment获取隐式参数 |
| 28 | +```java |
| 29 | +public class AttachmentServiceImpl implements AttachmentService { |
| 30 | + @Override |
| 31 | + public String sayHello(String name) { |
| 32 | + |
| 33 | + RpcContext context = RpcContext.getContext(); |
| 34 | + //获取客户端隐式传入的参数 |
| 35 | + String index = (String) context.getAttachment("index"); |
| 36 | + |
| 37 | + System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + name + |
| 38 | + ", request from consumer: " + context.getRemoteAddress()); |
| 39 | + return "Hello " + name + ", response from provider: " + context.getLocalAddress() + |
| 40 | + ", attachment - index: " + index; |
| 41 | + } |
| 42 | +} |
| 43 | +``` |
0 commit comments