Zookeeper和Consul作为注册中心

一.Zookeeper作为注册中心

1.导入依赖

<dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
        <version>2.3.3.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-actuatorartifactId>
        <version>2.3.0.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-zookeeper-discoveryartifactId>
    dependency>

2.编写yml文件

server:
  port: 8083

spring:
  cloud:
    zookeeper:
      connect-string: 192.168.43.158:2181   #我这里是用docker启动的zookeeper
  application:
    name: cloud-payment

3.配置启动类

@SpringBootApplication
@EnableDiscoveryClient
public class ZookeeperApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZookeeperApplication.class,args);
    }
}

4.编写一个服务,进行调用


@RestController
@RequestMapping("/zk")
public class ZKController {

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

    @RequestMapping("/get")
    public String getMessage(){
        return "zookeeper接受到的注册端口号为:"+serverPort+"\t"+ UUID.randomUUID().toString();
    }
}

5.调用第4步写好的服务

1.配置restTemplate

@Configuration
public class RestTempletConfig {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

2.调用服务

@RestController
@RequestMapping("/consumer")
public class ZKConsumerController {

    @Resource
    private RestTemplate restTemplate;

	//调用注册到zookeeper服务的名称,和eureka的用法查不到
    public static final String INVO_URL="http://cloud-payment";

    @RequestMapping("/zk/get")
    public String getMessage(){
        String forObject = restTemplate.getForObject(INVO_URL + "/zk/get", String.class);
        return forObject;
    }
}

5.查看zookeeper注册进来的服务

 1. 进入zookeeper容器内部(docker exec -it 容器id bash)
 2. 进入bin目录,进行客户端的启动(cd bin)
 3. 启动客户端(./zkCli.sh)
 4. 查看servers中注册的服务(ls /servers)

二.Consual作为注册中心

1.官网下载consual

2. 使用命令在cmd窗口启动(consul agent -dev)

3.图形化界面的查看(localhost:8500)

4.导入consual所需要的依赖

 <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-consul-discoveryartifactId>
    dependency>

5.编写yml文件

server:
  port: 80

spring:
  application:
    name: cloud-consumer

  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${spring.application.name}  #暴露出来的名称为自己的服务名称

6.其他的步骤就是服务的调用和zookeeper基本一样

你可能感兴趣的:(java,consul,zookeeper,spring,java)