TypechoJoeTheme

Jim Tse

【Dubbo】Spring Boot Dubbo Demo

本文最后更新于2023年05月06日,已超过502天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!

下载zookeeper作为注册中心

Zookeeper下载
解压并启动zookeeper

tar -zxf zookeeper-3.4.14.tar.gz
cd zookeeper-3.4.14
./bin/zkServer.sh start

新建dubbo-demo项目

pom.xml添加依赖

<dependencies>
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.11</version>
        </dependency>
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
        </dependency>
</dependencies>

项目新建dubbo-api、dubbo-provider和dubbo-consumer三个模块

dubbo-api

IHelloService.java

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

dubbo-provider

pom.xml

<dependencies>
        <dependency>
            <groupId>com.tse</groupId>
            <artifactId>dubbo-api</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

application.properties

spring.dubbo.appname=dubbo-provider
spring.dubbo.registry=zookeeper://localhost:2181

HelloServiceImpl.java

@Service
@Component
public class HelloServiceImpl implements IHelloService {
    public String sayHello(String name){
        return "hello" + name;
    }
}

Provider.java

@SpringBootApplication
@EnableDubboConfiguration
public class Provider {
    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(Provider.class,args);
        new CountDownLatch(1).await();
    }
}

dubbo-consumer

pom.xml

<dependencies>
        <dependency>
            <groupId>com.tse</groupId>
            <artifactId>dubbo-api</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.3.RELEASE</version>
        </dependency>
    </dependencies>

application.properties

spring.dubbo.appname=dubbo-consumer
spring.dubbo.registry=zookeeper://localhost:2181

HelloController

@RestController
@RequestMapping("/hello")
public class HelloController {
    @Reference
    IHelloService iHelloService;

    @RequestMapping
    public String hello(@RequestParam String name){
        return iHelloService.sayHello(name);
    }
}

Consumer.java

@SpringBootApplication
@EnableDubboConfiguration
public class Consumer {
    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(Consumer.class, args);
    }
}

赞(0)
版权属于:

Jim Tse

本文链接:

https://jimtse.eu.org:88/program/dubbo-demo.html(转载时请注明本文出处及文章链接)

评论 (0)