Springboot 项目也可以使用 Dubbo 了,方式比较简单,mark 下。
这里我们新建一个maven项目,然后下面对应建provider、consumer、api三个模块。
my-dubbo父项目中,我们加入dubbo的公共依赖,
org.apache.dubbo
dubbo-spring-boot-starter
2.7.3
org.apache.zookeeper
zookeeper
3.4.6
pom
com.101tec
zkclient
0.11
题外话,没有maven私服的话,也可以使用阿里云的maven库,比国外官网的快很多,
aliyun
aliyun Repository
http://maven.aliyun.com/nexus/content/groups/public
false
aliyunplugin
aliyunplugin Repository
http://maven.aliyun.com/nexus/content/groups/public
1、在启动类上,加上 @EnableDubboConfig 注解,
@SpringBootApplication
@EnableDubboConfig
public class DemoProviderApplication {
public static void main(String[] args) {
SpringApplication.run(DemoProviderApplication.class, args);
}
}
2、springboot项目yml配置文件中的dubbo配置,
server:
port: 8081
spring:
application:
name: provider
dubbo:
appname: provider
registry: zookeeper://127.0.0.1:2181
protocol: dubbo
port: 20880
3、在写接口实现类的时候,注意两个@Service注解(springboot的@Service注解和dubbo的@Service注解同名)的引用,一个用全称。
import com.spf.dubbo.demoapi.service.IBookService;
import org.apache.dubbo.config.annotation.Service;
@org.springframework.stereotype.Service
@Service(interfaceClass = IBookService.class, loadbalance = "roundrobin", weight = 60,
cluster = "failover", retries = 3, version = "1.0")
public class BookServiceImpl implements IBookService {
@Override
public String sayHello() {
return "Hello World";
}
}
1、在启动类上,加上 @EnableDubboConfig 注解,
@SpringBootApplication
@EnableDubboConfig
public class DemConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(DemConsumerApplication.class, args);
}
}
2、springboot项目yml配置文件中的dubbo配置,
server:
port: 9091
spring:
application:
name: consumer
dubbo:
appname: consumer
registry: zookeeper://127.0.0.1:2181
protocal: dubbo
port: 20880
3、消费者使用@Reference引用服务,
import com.spf.dubbo.demoapi.service.IBookService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
@Service
public class DubboService {
@Reference(interfaceClass = IBookService.class, loadbalance = "random", cluster = "failover",retries = 3, version = "1.0")
IBookService bookService;
public String test(){
return bookService.sayHello();
}
}
这里使用zookeeper作为注册中心,记得首先启动zk,然后provider、consumer。