Consul基本用法

1.简介:
      Consul 是 HashiCorp 公司推出的开源工具,用于实现分布式系统的服务发现与配置(注册中心)。Consul 使用 Go 语言编写,因此具有天然可移植性(支持Linux、windows和Mac OS X);安装包仅包含一个可执行文件,方便部署,与 Docker 等轻量级容器可无缝配合。
2. 遵循CP原则:
      Consul遵循了CP原则(一致性和分区容忍性),稍微丢失一些可用性:1. Consul的raft协议要求必须过半数的节点都写入成功才认为注册成功;2. Leader挂掉时,重新选举期间整个consul不可用。保证了强一致性但牺牲了可用性。
3. 开发语言及使用:
     Consul则是go编写而成,安装启动即可
4.下载:https://www.consul.io/downloads.html
5. 启动Consul服务:Windows:在consul的可执行文件下,进入dos命令窗口,执行以下命令。
#已开发者模式快速启动,-client指定客户端可以访问的ip地址;
#0.0.0.0表示所有ip都可以访问
[root@node01 ~]# consul agent -dev -client=0.0.0.0
6.进入到管理后台页面:http://127.0.0.1(consul的ip地址):8500/

入门案列:

  • 提供一个商品微服务(服务的提供者)
  • 提供一个订单系统(服务的消费者)

1.将微服务注册到注册中心Consul

    1.1 导入依赖:服务消费者以及服务提供者都要引入依赖
<!--springcloud 提供的对基于consul的服务发现-->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!--actuator的健康检查-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
    1.2 配置 :服务消费者以及服务提供者都要配置
#开始配置Consul的服务注册
cloud:
  consul:
    host: 127.0.0.1 #主机地址
    port: 8500 #consul的服务端口
    discovery:
      register: true #是否需要注册
      instance-id: ${spring.application.name}-1 #注册实例ID,唯一标志(-1主要保证唯一)
      service-name: ${spring.application.name} #服务的名称
      port: ${server.port} #服务的请求端口
      prefer-ip-address: true #指定开启ip地址注册
      ip-address: ${spring.cloud.client.ip-address} #当前服务请求IP

2.服务的消费者从Consul中拉取所有的服务列表

  • 引入上方依赖以及配置之后,在操作。
  • Consul内部集成了Ribbon:使用服务名称代替IP地址以及端口号
    2.1 在服务消费者启动类的RestTemplate上方加@LoadBalanced注解
@SpringBootApplication
@EntityScan("cn.itcast.order.entity")
public class OrderApplication {


   /**
    * springcloud对consul进行了进一步的处理
    *  向其中集成了ribbon的支持
    */

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

   public static void main(String[] args) {
   	SpringApplication.run(OrderApplication.class,args);
   }
}
    2.2 使用服务提供者名称调用服务提供者
@RestController
@RequestMapping("/order")
public class OrderController {

   @Autowired
   private RestTemplate restTemplate;

   @RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)
   public Product findById(@PathVariable Long id) {
    //使用服务提供者名称调用服务提供者
   	Product product = restTemplate.getForObject("http://service-product/product/"+id,Product.class);
   	return product;
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值