springboot整合dubbo

2020-06-04   76 次阅读


  • 导入相关依赖
        <!--dubbo-->
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.7.7</version>
        </dependency>
        <!--zkclient-->
        <dependency>
            <groupId>com.github.sgroschupf</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.1</version>
        </dependency>
        <!--zkserver 相关依赖-->
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.14</version>
            <type>pom</type>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-jdk14</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

1. provider(提供者)

pom.xml

server.port=8081
#服务应用名字
dubbo.application.name=provider
#注册中心地址
dubbo.registry.address=zookeeper://127.0.0.1:2181
#被注册的服务
dubbo.scan.base-packages=cn.hm1006.service

TicketService及实现类

package cn.hm1006.service;

public interface TicketService {
    String getTicket();
}
package cn.hm1006.service;

import org.springframework.stereotype.Component;

@Component
public class TicketServiceImpl implements TicketService {

    @Override
    public String getTicket() {
        return "卖票";
    }
}

2. consumer(消费者)

application.properties

server.port=8082
#消费者的名字
dubbo.application.name=consumer
#注册中心地址
dubbo.registry.address=zookeeper://127.0.0.1:2181

调用provider
UserService

package cn.hm1006.service;

import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Reference////引用, Pom坐标,可以定义路经相同的接口名,无需实现方法
    TicketService ticketService;

    public void buyTicket(){
        String ticket = ticketService.getTicket();
        System.out.println(ticket);
    }
}
package cn.hm1006.service;

public interface TicketService {
    String getTicket();
}

Q.E.D.

知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

如人饮水、冷暖自知