通用zookeeper 服务注册接口-学习记录(五)

  • 2019-05-26 18:34:12
  • 310
  • 0


application.properties 配置文件:


server.address=127.0.0.1
server.port=8080
zkregistry.servers=127.0.0.1:2181

1 编写接口类 ServiceRegistry


public interface ServiceRegistry {
    /**
     *
     * @param serviceName 服务名称
     * @param serviceAddress  服务地址
     */
    void register(String serviceName,String serviceAddress);
}


2 编写实现类 ServiceRegistryImpl


import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.concurrent.CountDownLatch;
@Component
public class ServiceRegistryImpl implements  ServiceRegistry ,Watcher{
    private static Logger logger = LoggerFactory.getLogger(ServiceRegistryImpl.class);
    private  static CountDownLatch latch = new CountDownLatch(1);
    private ZooKeeper zooKeeper;
    private static final int SESSION_TIME = 5000;
    private static final String REGISTRY_PATH = "/registryRoot";
    public ServiceRegistryImpl() {
    }
    public ServiceRegistryImpl(String zookServers) {
         try{
             //创建链接
             zooKeeper = new ZooKeeper(zookServers,SESSION_TIME,this);
             latch.await();
             logger.debug("创建链接成功");
         }catch(Exception e){
            logger.error("创建链接异常",e);
         }
    }
    @Override
    public void process(WatchedEvent watchedEvent) {
        if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
            latch.countDown();
        }
    }
    @Override
    public void register(String serviceName, String serviceAddress) {
        try{
            //创建根节点
            String regsitryPath = REGISTRY_PATH;
            if(zooKeeper.exists(regsitryPath,false) == null){
                zooKeeper.create(regsitryPath,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                logger.debug("创建根节点成功,{}",regsitryPath);
            }
            //创建服务节点
            String servicePath = regsitryPath  "/"   serviceName ;
            if(zooKeeper.exists(servicePath,false)==null){
                zooKeeper.create(servicePath,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                logger.debug("创建服务节点成功,{}",servicePath);
            }
            //创建地址节点(临时顺序节点)
            String addressPath = servicePath  "/address-";
            String addressNode = zooKeeper.create(addressPath,serviceAddress.getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
            logger.debug("创建地址节点成功,{} ==》 {}",addressNode,serviceAddress);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}


3 编写 配置类来注入节点ip和端口号  RegistryConfig


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "zkregistry")
public class RegistryConfig {
    private String servers;
    @Bean
    public ServiceRegistry serviceRegistry(){
        return new ServiceRegistryImpl(servers) ;
     }
    public void setServers(String servers) {
        this.servers = servers;
    }
}


4 应用初始化的时候去完成服务注册 WebListener


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Map;

@Component
public class WebListener implements ServletContextListener {
    @Value("${server.address}")
    private String serverAddress;

    @Value("${server.port}")
    private int serverPort;

    @Autowired
    private ServiceRegistry serviceRegistry;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //获取请求映射
        ServletContext servletContext = sce.getServletContext();
        ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo,HandlerMethod> infoMap = mapping.getHandlerMethods();
        for(RequestMappingInfo info:infoMap.keySet()){
            String serviceName = info.getName();
            if(serviceName != null){
                //注册服务
                serviceRegistry.register(serviceName,String.format("%s:%d",serverAddress,serverPort));
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}


//启动类:


@SpringBootApplication
@RestController
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }

   @RequestMapping(name = "HelloService")
   public String hello(){
      return "hello";
   }
}



POM 类


<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.1.5.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.example</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <properties>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
      <dependency>
         <groupId>org.apache.zookeeper</groupId>
         <artifactId>zookeeper</artifactId>
         <version>3.4.14</version>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
         <!-- 跳过单元测试 -->
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
               <skipTests>true</skipTests>
            </configuration>
         </plugin>
      </plugins>
   </build>

</project>





回复
举报
全部回复(0)

参与讨论