3

Dubbo 在 Spring 中的使用案例

 1 year ago
source link: https://www.jansora.com/notebook/107610
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Dubbo 在 Spring 中的使用案例Dubbo 在 Spring 中的使用案例导航前往主站应用闲文杂记知识专栏代码在线代码魔方房价浅析小简助手

Dubbo是阿里巴巴开源的一个高性能、轻量级的分布式服务框架。Dubbo提供了全面的服务治理解决方案和丰富的服务治理策略,包括服务注册与发现、服务路由、服务负载均衡、服务降级与熔断、服务热部署等。

以下是一个使用Dubbo在Spring中的基本例子:

1. 添加依赖

首先,在项目的pom.xml文件中添加dubbo和spring相关的依赖:

<dependencies>
    <dependency>
        <groupId>org.apache.dubbo</groupId>
        <artifactId>dubbo</artifactId>
        <version>2.7.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.dubbo</groupId>
        <artifactId>dubbo-spring-boot-starter</artifactId>
        <version>2.7.8</version>
    </dependency>
</dependencies>

2. 创建服务接口

在提供者项目中创建服务接口:

public interface HelloService {
    String sayHello(String name);
}

3. 创建服务实现

在提供者项目中创建服务接口的实现:

import org.apache.dubbo.config.annotation.DubboService;

@DubboService
public class HelloServiceImpl implements HelloService {
    @Override
    public String sayHello(String name) {
        return "Hello, " + name;
    }
}

4. 提供者配置

在application.properties文件中添加服务提供者的配置:

dubbo.application.name=provider
dubbo.registry.address=zookeeper://127.0.0.1:2181

5. 消费者配置

在消费者的application.properties文件中添加服务消费者的配置:

dubbo.application.name=consumer
dubbo.registry.address=zookeeper://127.0.0.1:2181

6. 消费者使用服务

在消费者项目中,使用@DubboReference注解来引用服务:

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @DubboReference
    private HelloService helloService;

    @GetMapping("/hello/{name}")
    public String sayHello(@PathVariable("name") String name) {
        return helloService.sayHello(name);
    }
}

注意,以上示例需要你已经有一个运行的Zookeeper服务作为服务注册与发现的中心。如果你没有,你可以使用其他的服务注册与发现中心,只需修改dubbo.registry.address的值即可。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK