SpringBoot 整合 Dubbo 进行分布式开发


 

自从Dubbo支持SpringBoot后,Dubbo与Spring的整合变得更加的简单了,下面就是完整的步骤:

 

1. 引入依赖

<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
    <version>0.2.0</version>
</dependency>

 

2. 在dubbo-api中定义model和service接口,model就是普通的POJO,service接口的代码如下:

BounterService.java

package cn.bounter.dubbo.service;

import cn.bounter.dubbo.model.Bounter;

public interface BounterService {
    
    Bounter findById(long id);
}

 

3. 服务提供者实现接口并配置Dubbo

BounterServiceImpl.java

package cn.bounter.dubbo.service;


import java.util.Date;
import com.alibaba.dubbo.config.annotation.Service;
import cn.bounter.dubbo.model.Bounter;


//声明为Dubbo服务
@Service
public class BounterServiceImpl implements BounterService {

    @Override
    public Bounter findById(long id) {
        //模拟访问数据库
        return new Bounter().setId(1L).setName("simon").setCreateTime(new Date()).setCreateBy(1L);
    }

}

 

application.properties

## Application
server.port=28080

## Dubbo
dubbo.application.name=dubbo-provider
dubbo.registry.address=zookeeper://47.98.151.249:2181
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
dubbo.scan.basePackages=cn.bounter

 

4. 服务消费者配置Dubbo并调用Dubbo服务

application.properties

# Application
server.port=18080

## Dubbo
dubbo.application.name=dubbo-consumer
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo.scan=cn.bounter

 

BounterController.java

package cn.bounter.dubbo.controller;


import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;

import cn.bounter.dubbo.model.ResponseData;
import cn.bounter.dubbo.service.BounterService;

@RestController
@CrossOrigin
@RequestMapping("/api/bounter")
public class BounterController {
    
    @Reference
    private BounterService bounterService;


    @GetMapping("/{id}")
    public ResponseData<?> get(@PathVariable Long id) {
        return new ResponseData<>().success().data(bounterService.findById(id));
    }

}

 

这样当你依次启动dubbo-provider和dubbo-consumer之后,浏览器访问http://localhost:18080/api/bounter/1就可以看到效果了

需要完整代码的请移步我的Github: 
https://github.com/13babybear/bounter-springboot-dubbo

posted @ 2018-08-03 15:21  二十六度半  阅读(4707)  评论(1编辑  收藏  举报