步骤1:下载ZooKeeperhtml
要在你的计算机上安装ZooKeeper框架,请访问如下连接并下载最新版本的ZooKeeper。http://zookeeper.apache.org/releases.htmljava
到目前为止,最新版本的ZooKeeper是3.4.6(ZooKeeper-3.4.6.tar.gz)。git
步骤2:提取tar文件github
$ cd opt/
$ tar -zxf zookeeper-3.4.6.tar.gz
$ cd zookeeper-3.4.6
$ mkdir data
步骤3:建立配置文件spring
$ vi conf/zoo.cfg
tickTime = 2000
dataDir = /path/to/zookeeper/data
clientPort = 2181
initLimit = 5
syncLimit = 2
步骤4:启动ZooKeeper服务器apache
$ bin/zkServer.sh start
$ JMX enabled by default
$ Using config: /Users/../zookeeper-3.4.6/bin/../conf/zoo.cfg
$ Starting zookeeper ... STARTED
<!--Dubbo与SpringBoot的集成 -->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>0.1.0</version>
</dependency>
<!-- zookeeper客户端 -->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
新建模块provider-ticket并导入步骤2的包编程
1)在目录下新建service包,在该包下新建一个接口类ruby
package cn.zyzpp.ticket.service;
public interface TicketService {
String getTicket();
}
package cn.zyzpp.ticket.service;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;
/** * Create by yster@foxmail.com 2018/6/4/004 15:57 */
@Component //Spring注解
@Service //dubbo的注解
public class TicketServiceImpl implements TicketService {
@Override
public String getTicket() {
return "<<厉害了,个人国>>";
}
}
server:
port: 8082
dubbo:
application:
name: provider-ticket
registry:
address: zookeeper://127.0.0.1:2181
scan:
base-packages: cn.zyzpp.ticket.service
总结服务器
将服务提供者注册到注册中心-->
1.引入Dubbo和Zookeeper的相关依赖
2.配置Dubbo的扫描包和注册中心地址
3.使用@Service发布服务
新建模块consumer-user并导入步骤2的包架构
1)配置application.yml
server:
port: 8081
dubbo:
application:
name: consumer-user
registry:
address: zookeeper://127.0.0.1:2181
package cn.zyzpp.ticket.service;
/*必须保证客户端与服务端的类路径一致,只保留该接口类便可。*/
public interface TicketService {
String getTicket();
}
package cn.zyzpp.user.service;
import cn.zyzpp.ticket.service.TicketService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
@Service
public class UserSerivce{
@Reference /*引用接口需注解dubbo的@Reference*/
private TicketService ticketService;
public void getHello(){
String ticket = ticketService.getTicket();
System.out.println("买到票了:" + ticket);
}
}
package cn.zyzpp;
import cn.zyzpp.user.service.UserSerivce;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ConsumerUserApplicationTests {
@Autowired
private UserSerivce userSerivce;
@Test
public void contextLoads() {
userSerivce.getHello();
}
}