本节将以一个实际例子来学习一下使用SpringBoot+Zookeeper来构建微服务之服务的注册。
首先学习本文之前请先了解 SpringBoot整合Mybatis。
创建一个合同(Contract)服务模块。
项目结构
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.sstps.springBootgroupId>
<artifactId>ContractartifactId>
<version>0.0.1-SNAPSHOTversion>
<packaging>jarpackaging>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<Maven.compiler.source>1.8Maven.compiler.source>
<Maven.compiler.target>1.8Maven.compiler.target>
properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-dependenciesartifactId>
<version>1.5.8.RELEASEversion>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.1version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.apache.curatorgroupId>
<artifactId>curator-x-discovery-serverartifactId>
<version>2.11.0version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-actuatorartifactId>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojogroupId>
<artifactId>appassembler-maven-pluginartifactId>
<version>1.10version>
<configuration>
<platforms>
<platform>windowsplatform>
<platform>unixplatform>
platforms>
<assembleDirectory>${project.build.directory}/marketassembleDirectory>
<repositoryName>librepositoryName>
<binFolder>binbinFolder>
<configurationDirectory>confconfigurationDirectory>
<copyConfigurationDirectory>truecopyConfigurationDirectory>
<configurationSourceDirectory>src/main/resourcesconfigurationSourceDirectory>
<repositoryLayout>flatrepositoryLayout>
<encoding>UTF-8encoding>
<logsDirectory>logslogsDirectory>
<tempDirectory>tmptempDirectory>
<programs>
<program>
<id>marketid>
<mainClass>com.sstps.market.AppmainClass>
<jvmSettings>
<extraArguments>
<extraArgument>-serverextraArgument>
<extraArgument>-Xmx2GextraArgument>
<extraArgument>-Xms2GextraArgument>
extraArguments>
jvmSettings>
program>
programs>
configuration>
plugin>
plugins>
build>
project>
ServiceRegistor.java
package com.sstps.market;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class ServiceRegistor implements ApplicationRunner {
@Value("${zookeeper.address}")
private String registerAddress;
@Value("${service.address}")
private String serviceAddress;
@Value("${service.port}")
private Integer servicePort;
public void run(ApplicationArguments args) throws Exception {
//注册中心
CuratorFramework client = CuratorFrameworkFactory.newClient(registerAddress, new RetryOneTime(1000));
client.start();
client.blockUntilConnected();
//注册服务
ServiceInstance
代码解读:使用 CuratorFramework 来实现服务的注册。Curator对Zookeeper JAVA API做了高度封装。
application.properties
spring.datasource.url=jdbc:mysql:///sstps_product?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=bai5331359
spring.datasource.tomcat.driver-class-name=com.mysql.jdbc.Driver
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
server.port=9090
zookeeper.address=192.168.100.19:2181
service.address=192.168.100.19
service.port=9090
management.security.enabled=false
其他java代码就是基本SSM业务逻辑代码来实现增删改查的基本功能,这里就不展示了。核心代码在服务的注册。
App.java
package com.sstps.market;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import com.sstps.market.entity.Contract;
import com.sstps.market.mapper.ContractMapper;
@SpringBootApplication
@ComponentScan("com.sstps.market")
public class App {
/**
* 微服务, 把原来一个大的系统拆分成小的系统,每一小的系统 单独 开发。测试、维护
*
* 常用的服务注册中心有: Zookeeper、consul、etcd、redis
* 服务提供方需要在服务启动的时候把服务的信息注册到注册中心去(Zookeeper)。
* @param args
*/
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
context.getBean(ContractMapper.class);
}
}
创建一个市场模块(Market)
项目结构
application.properties
spring.datasource.url=jdbc:mysql:///sstps_product?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=bai5331359
spring.datasource.tomcat.driver-class-name=com.mysql.jdbc.Driver
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
zookeeper.address=192.168.100.19:2181
service.address=192.168.100.19
service.port=8080
management.security.enabled=false
ServiceRegistor.java
package com.sstps.market;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class ServiceRegistor implements ApplicationRunner {
@Value("${zookeeper.address}")
private String registerAddress;
@Value("${service.address}")
private String serviceAddress;
@Value("${service.port}")
private Integer servicePort;
public void run(ApplicationArguments args) throws Exception {
//注册中心
CuratorFramework client = CuratorFrameworkFactory.newClient(registerAddress, new RetryOneTime(1000));
client.start();
client.blockUntilConnected();
//注册服务
ServiceInstance instance = ServiceInstance.builder().name("market").address(serviceAddress).port(servicePort).build();
ServiceDiscovery serviceDiscovery = ServiceDiscoveryBuilder.builder(Object.class).client(client).basePath("/sstps").build();
serviceDiscovery.registerService(instance);
serviceDiscovery.start();
System.out.println("Registe successed");
}
}
App.java
package com.sstps.market;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.Transactional;
import com.sstps.market.mapper.ProductMapper;
@SpringBootApplication
@ComponentScan("com.sstps.market")
public class App {
/**
* 微服务, 把原来一个大的系统拆分成小的系统,每一小的系统 单独 开发。测试、维护
*
* 常用的服务注册中心有: Zookeeper、consul、etcd、redis
* 服务提供方需要在服务启动的时候把服务的信息注册到注册中心去(Zookeeper)。
* @param args
*/
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
context.getBean(ProductMapper.class);
}
}
开启Zookeeper服务(以windos OS 为例)
首先现在本安装一个Zookeeper的服务,关于zookeeper将在以后讲解,请关注本人csdn微博~
启动Contract 和 Market两个服务,然后查看Zookeeper。
此时我们的服务边注册到了Zookeeper中去了。
微服务的注册使用的是 Curator,当然你也可以使用ZClient等。因人而异。
服务的注册核心代码:
使用 CuratorFramework 来实现服务的注册因为 Curator 提供了更为高效简介易用的 JAVA API。
实现ApplicationRunner接口。该接口中的实现类的方法将在 SpringBoot 启动服务以后调用。