本文参考孙卫琴,杜聚宾所创作的<<Spring Cloud Alibaba微服务开发宝典>>一书,即将出版 在Dubbo框架中,消费者可以远程调用提供者的服务方法。此外,提供者也可以调用消费者的方法,这种调用过程称为回调。/* 例程1  CallbackListener.java */ public  interface  CallbackListener {//这是提供者回调消费者的方法   public  void  report(String msg); 
//提供者的服务方法 public  String sayHello(String username,String key);//消费者通过此方法向提供者注册CallbackListener public  void  addListener(String key, 
/* 例程2  MyCallbackListener.java */ public  class  MyCallbackListener implements  CallbackListener{public  void  report(String msg) {
@Value("${server.port}")private  String servicePort;//该注解表示Spring框架创建了控制器对象后就会调用init()方法 @PostConstruct   public  void  init(){//向提供者注册MyCallbackListener对象,以servicePort作为key   helloService.addListener(servicePort,new  MyCallbackListener());public  String testCallback(@PathVariable String username){//调用提供者的sayHello()服务方法   return  helloService.sayHello(username,servicePort); 
/* 例程3  HelloServiceImpl.java */ //指明addListener()方法的listener参数是回调类型的参数   methods={public  class  HelloServiceImpl implements  HelloService {//存放消费者所注册的CallbackListener对象   private  final  Map<String, CallbackListener> listeners = new  ConcurrentHashMap<String, CallbackListener>();public  HelloServiceImpl() {//创建定时向消费者推送当前时间信息的线程     Thread t = new  Thread(new  Runnable() {public  void  run() {while (true ){try {for (Map.Entry<String, CallbackListener> entry : try {//回调消费者的CallbackListener的report()方法                 entry.getValue().report("当前时间:"new  Date());catch  (Throwable t) {//通过睡眠定时向消费者推送时间信息           }catch  (Throwable ex){ true );   //作为后台线程运行     t.start();public  void  addListener(String key, //加入消费者注册的CallbackListener对象     listeners.put(key, listener);  public  String sayHello(String username,String key){//回调消费者的CallbackListener对象的report()方法      listener.report(username+"打过招呼。");return  "Hello," + username;
当前时间:Fri May 27 13:25:38 CST 2022 
 
        
      
 
网站系统异常 
    
     系统异常信息  
    
     
       
         Request URL: 
http://www.javathinker.net/WEB-INF/lybbs/jsp/topic.jsp?postID=4208本站管理人员 。