服務調用和響應時,除了請求的方法和返回的響應,還可以通過上下文(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