服务调用和响应时,除了请求的方法和返回的响应,还可以通过上下文(Context)传递更多的数据(附加数据)
一、接口定义
package cn.edu.tju.service;public interface ContextService {String invoke(String param);
}
二、服务端接口实现:
package cn.edu.tju.service;import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.rpc.RpcContext;import java.util.Map;@DubboService
public class ContextServiceImpl implements ContextService{@Overridepublic String invoke(String param) {//接收客户端传递过来的附加数据Map<String, Object> serverAttachments = RpcContext.getServerAttachment().getObjectAttachments();System.out.println("【from client】:" + JSON.toJSONString(serverAttachments));//往客户端传递数据System.out.println("【to client】: hi world");RpcContext.getServerContext().setAttachment("hi","world");StringBuilder s = new StringBuilder();s.append("response:").append(param);return s.toString();}
}
其中除了正常的响应之外,还通过上下文传递了hi world。
三、客户端调用
package cn.edu.tju.service;import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcContextAttachment;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;import java.util.Map;@Component
public class ContextConsumer implements CommandLineRunner {@DubboReferenceprivate ContextService contextService;@Overridepublic void run(String... args) throws Exception {// 向服务器传递附加数据System.out.println("【to server】 hello,world");RpcContext.getClientAttachment().setAttachment("hello","world");String res = contextService.invoke("this is a book");//读取从服务器端返回的附加数据Map<String, Object> clientAttachment = RpcContext.getServerContext().getObjectAttachments();System.out.println("【from server】" + JSON.toJSONString(clientAttachment));System.out.println("调用结果 : " + res);}
}
会向服务器发送hello world,同时,会收到服务器端返回的hi world