dubbo复习:(14)通过上下文传递附加数据

服务调用和响应时,除了请求的方法和返回的响应,还可以通过上下文(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{
    @Override
    public 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 {
    @DubboReference
    private ContextService contextService;

    @Override
    public 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值