Skip to content

Commit e50acee

Browse files
committed
add dubbo attachment readme
1 parent 3296eab commit e50acee

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,6 @@
1717
- ##### [分布式服务框架Dubbo(缓存策略)](https://github.com/ipipman/JavaSpringBootSamples/tree/master/dubbo-cache-sample "分布式服务框架Dubbo(缓存策略)")
1818
- ##### [分布式服务框架Dubbo(参数回调)](https://github.com/ipipman/JavaSpringBootSamples/tree/master/dubbo-callback-sample "分布式服务框架Dubbo(参数回调)")
1919
- ##### [分布式服务框架Dubbo(基于HTTP传输协议)](https://github.com/ipipman/JavaSpringBootSamples/tree/master/dubbo-http-sample "分布式服务框架Dubbo(基于HTTP传输协议)")
20-
- ##### [分布式服务框架Dubbo(本地调用)](https://github.com/ipipman/JavaSpringBootSamples/tree/master/dubbo-local-sample "分布式服务框架Dubbo(本地调用)")
20+
- ##### [分布式服务框架Dubbo(本地调用)](https://github.com/ipipman/JavaSpringBootSamples/tree/master/dubbo-local-sample "分布式服务框架Dubbo(本地调用)")
21+
- ##### [分布式服务框架Dubbo(隐式参数)](https://github.com/ipipman/JavaSpringBootSamples/tree/master/dubbo-attachment-sample "分布式服务框架Dubbo(隐式参数)")
22+

dubbo-attachment-sample/README.md

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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

Comments
 (0)