本节将阐述在springboot下完成基于buddo、zookeeper的分布式。
1、环境约束
- win10 64位操作系统
- idea2018.1.5
- maven-3.0.5
- jdk-8u162-windows-x64
2、前提约束
- 能使用springboot创建web项目 https://www.jianshu.com/p/de979f53ad80
注意,作者使用的springboot版本是2.1.8.RELEASE - 已经搭建zookeeper服务,假设zookeeper服务在本地,即 127.0.0.1:2181
3、操作步骤
- 创建一个maven项目,作为父项目,名称为springboot-dubbo-zookeeper[普通非web类型]
- 在父项目下创建sdz-pojo子module[普通非web类型],在其中创建User.java
import java.io.Serializable;
public class User implements Serializable {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 在父项目下创建sdz-interface子module[普通非web类型],在其中创建UserService.java
package net.wanho.springboot.service;
import net.wanho.springboot.pojo.User;
public interface UserService {
User get();
}
- 在父项目想创建sdz-provider子module[boot web类型]
(1)修改application.properties
server.port=8083
spring.dubbo.application.name=producer
spring.dubbo.registry.address=zookeeper://localhost:2181
spring.dubbo.protocol.name=dubbo
spring.dubbo.protocol.port=20880
#这个路径与接口sdz-interface中的接口所在包一致
spring.dubbo.scan=net.wanho.springboot.service
#属性
user.name=ali
user.id=101
(2)创建UserServiceImpl.java
package net.wanho.springboot.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import net.wanho.springboot.pojo.User;
import net.wanho.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Value;
@Service
public class UserServiceImpl implements UserService {
@Value("${user.id}")
private int id;
@Value("${user.name}")
private String name;
@Override
public User get() {
return new User(id, name);
}
}
- 在父项目想创建sdz-consumer子module[boot web类型]
(1)修改application.properties
server.port=8084
spring.dubbo.application.name=consumer
spring.dubbo.registry.address=zookeeper://localhost:2181
# 这个路径与本项目中service包路径相同
spring.dubbo.scan=net.wanho.springboot.consumer
(2)创建HelloService.java
package net.wanho.springboot.consumer;
import com.alibaba.dubbo.config.annotation.Reference;
import net.wanho.springboot.pojo.User;
import net.wanho.springboot.service.UserService;
import org.springframework.stereotype.Service;
@Service //spring的Service注解
public class HelloService {
@Reference //这里是dubbo的注解
UserService userService;
public User get() {
return userService.get();
}
}
(3)创建HelloController.java
import net.wanho.springboot.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
@Controller
public class HelloController {
@Resource
HelloService helloService;
@RequestMapping("hello")
@ResponseBody
public User get(){
return helloService.get();
}
}
- 分别启动,测试,访问http://localhost:8084/hello。