- 一、项目结构
- 二、接口工程
- 三、服务提供者
- 四、服务消费者
- 五、总结
001-interface:表示接口工程
boot-provider: 表示服务提供者
boot-consumer: 表示服务消费者
明确接口工程为java工程,需要将该工程打成jar包,供提供者和消费者使用
打包步骤
- HelloService
public interface HelloService {
public String sayHello();
}
- pom.xml
三、服务提供者4.0.0 com.cjw.dubbo 001-interface 1.0-SNAPSHOT jar
- HelloServiceImpl :接口实现类
import com.cjw.dubbo.service.HelloService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;
@Service //将服务暴露出去
@Component //将服务注册在容器中
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello() {
return "boot-provider-sayHello";
}
}
- BootProviderApplication
@EnableDubbo //开启dubbo注解
@SpringBootApplication
public class BootProviderApplication {
public static void main(String[] args) {
SpringApplication.run(BootProviderApplication.class, args);
}
}
- application.properties
#端口号 server.port=8082 #注册提供者 dubbo.application.name=boot-provider #注册服务到zookeeper中 dubbo.registry.address=zookeeper://localhost:2181 #协议端口号为20880 dubbo.protocol.port=20880 #使用协议为dubbo dubbo.protocol.name=dubbo
- pom.xml
org.apache.dubbo
dubbo-spring-boot-starter
2.7.3
org.apache.curator
apache-curator
2.12.0
org.apache.curator
curator-recipes
2.12.0
org.apache.zookeeper
zookeeper
3.4.14
org.slf4j
slf4j-log4j12
com.cjw.dubbo
001-interface
1.0-SNAPSHOT
四、服务消费者
1.HelloDubboController
import com.cjw.dubbo.service.HelloService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloDubboController {
@Reference //远程引用指定的服务,他会按照全类名进行匹配,看谁给注册中心注册了这个全类名
private HelloService helloService;
@RequestMapping("/hello")
@ResponseBody
public String getHello() {
String sayHello = helloService.sayHello();
System.out.println("sayHello = " + sayHello);
return sayHello;
}
}
- BootConsumerApplication
@EnableDubbo //开启dubbo注解
@SpringBootApplication
public class BootConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(BootConsumerApplication.class, args);
}
}
- application.properties
#端口号 server.port=8083 #注册服务消费者 dubbo.application.name=boot-consumer #使用zookeeper 接收服务 dubbo.registry.address=zookeeper://localhost:2181
- pom.xml
org.apache.dubbo
dubbo-spring-boot-starter
2.7.3
org.apache.curator
apache-curator
2.12.0
org.apache.curator
curator-recipes
2.12.0
org.apache.zookeeper
zookeeper
3.4.14
org.slf4j
slf4j-log4j12
com.cjw.dubbo
001-interface
1.0-SNAPSHOT
五、总结
- 注意. @Reference 表示远程引用指定的服务,他会按照全类名进行匹配,看谁给注册中心注册了这个全类名
- @Service //将服务暴露出去 包名为org.apache.dubbo.config.annotation.Service
- @EnableDubbo //开启dubbo注解



