步驟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();
}
}