一个简单的Dubbo工程样例

kevingrace 阅读:474 2023-04-23 09:45:57 评论:0

这是一个简单的Dubbo工程样例,包括了Dubbo服务提供者和消费者的代码示例。

1. Dubbo服务提供者

java 
package com.example.dubbo.provider; 
 
import com.example.dubbo.api.HelloService; 
import org.apache.dubbo.config.annotation.Service; 
 
@Service(version = "1.0.0") 
public class HelloServiceImpl implements HelloService { 
 
    @Override 
    public String sayHello(String name) { 
        return "Hello, " + name; 
    } 
} 

2. Dubbo服务消费者

java 
package com.example.dubbo.consumer; 
 
import com.example.dubbo.api.HelloService; 
import org.apache.dubbo.config.annotation.Reference; 
import org.springframework.stereotype.Component; 
 
@Component 
public class HelloConsumer { 
 
    @Reference(version = "1.0.0") 
    private HelloService helloService; 
 
    public void sayHello(String name) { 
        String result = helloService.sayHello(name); 
        System.out.println(result); 
    } 
} 

3. Dubbo配置文件

xml 

   

   

   

   

   

4. 测试代码

java 
package com.example.dubbo; 
 
import com.example.dubbo.consumer.HelloConsumer; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
 
public class DubboDemoApplication { 
 
    public static void main(String[] args) { 
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:dubbo-consumer.xml"); 
        context.start(); 
 
        HelloConsumer helloConsumer = context.getBean(HelloConsumer.class); 
        helloConsumer.sayHello("Dubbo"); 
 
        context.close(); 
    } 
} 

以上代码示例中,服务提供者实现了一个简单的接口HelloService,服务消费者通过Dubbo的@Reference注解引用了该接口,并调用了其中的方法。Dubbo的配置文件中指定了服务注册中心和协议等信息。最后,在测试代码中启动了Spring容器,并调用了服务消费者的方法。


标签:Dubbo
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号