- 一、接口工程
- 1.1、创建maven Java工程
- 1.2、添加实体类和服务接口
- 二、服务提供者
- 2.1、创建springboot工程
- 2.2、添加相关依赖
- 2.3、配置springboot核心配置文件
- 2.4、编写接口实现类
- 2.5、开启dubbo配置
- 三、服务消费者
- 3.1、创建spring boot工程
- 3.2、添加相关依赖
- 3.3、配置springboot核心配置文件
- 3.4、编写Controller
- 3.5、开启dubbo配置
- 测试
- 启动zookeeper注册中心
- 关闭防火墙
- 运行结果
- 实体类
@Data
public class Student implements Serializable {
private Integer id;
private String name;
private String sex;
private Integer age;
}
- 服务接口
public interface StudentService {
//通过id查询学生
Student queryStudent(Integer id);
}
二、服务提供者
2.1、创建springboot工程
2.2、添加相关依赖
添加dubbo、注册中心、接口工程依赖
2.3、配置springboot核心配置文件com.why ch04-springboot-dubbo-interface 1.0-SNAPSHOT com.alibaba.spring.boot dubbo-spring-boot-starter 2.0.0 com.101tec zkclient 0.10
在application.properties文件中编写
#内嵌tomcat配置 server.port=8081 server.servlet.context-path=/ #dubbo配置 #服务提供者名称 spring.application.name=ch04-dubbo-provide #声明当前工程是服务提供者 spring.dubbo.server=true #注册中心 默认端口号2181 spring.dubbo.registry=zookeeper://192.168.140.129:21812.4、编写接口实现类
//把接口的实现类(服务)交给springboot容器管理
@Component
//@Service选择alibaba提供的那个 interfaceName接口的全限定名 也可以使用interfaceClass
//@Service(interfaceClass = StudentService.class,version = "1.0.0",timeout = 15000)
//暴露接口服务
@Service(interfaceName = "com.why.service.StudentService",version = "1.0.0",timeout = 15000)
public class StudentServiceImpl implements StudentService {
@Override
public Student queryStudent(Integer id) {
//这里只是通过创建对象来模拟dao层访问数据库返回的结果
//偷个小懒
Student student = new Student();
student.setName("张三");
student.setSex("男");
student.setAge(21);
return student;
}
}
2.5、开启dubbo配置
在引导类上添加@EnableDubboConfiguration注解
@SpringBootApplication
@EnableDubboConfiguration//开启dubbo配置
public class Ch04SpringbootDubboProvideApplication {
public static void main(String[] args) {
SpringApplication.run(Ch04SpringbootDubboProvideApplication.class, args);
}
}
三、服务消费者
3.1、创建spring boot工程
3.2、添加相关依赖
添加dubbo、注册中心、接口工程依赖
3.3、配置springboot核心配置文件com.why ch04-springboot-dubbo-interface 1.0-SNAPSHOT com.alibaba.spring.boot dubbo-spring-boot-starter 2.0.0 com.101tec zkclient 0.10
#内嵌tomcat端口号 server.port=8080 #上下文根 server.servlet.context-path=/ #duoob配置 #服务消费者名称 spring.application.name=ch04-springboot-dubbo-consumer #注册中心 spring.dubbo.registry=zookeeper://192.168.140.129:21813.4、编写Controller
@Controller
public class MyController {
//引用服务提供者提供的服务
@Reference(interfaceName = "com.why.service.StudentService",version = "1.0.0",check = false)
StudentService studentService;
@RequestMapping("/query")
public @ResponseBody Object query(){
Student student = studentService.queryStudent(1);
return student.toString();
}
}
3.5、开启dubbo配置
在引导类上添加@EnableDubboConfiguration注解
@SpringBootApplication
@EnableDubboConfiguration//开启dubbo配置
public class Ch04SpringbootDubboConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(Ch04SpringbootDubboConsumerApplication.class, args);
}
}
测试
启动zookeeper注册中心
关闭防火墙
- ./zkServer.sh start //在zookeeper的bin目录下执行
运行结果
- systemctl stop firewalld //关闭防火墙



