SpringBoot 整合 Dubbo 进行分布式开发

2018-08-05 07:45:28来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折


 

自从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

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:java自学 day6

下一篇:Spring Cloud中异常处理的套路