Consul

原创
2020/03/23 13:29
阅读数 1.4K

官网地址: https://www.consul.io/intro/index.html 

spring cloud 集成consul : https://www.springcloud.cc/spring-cloud-consul.html

consul的启动安装   下载文件,解压,启动命令   consul agent -dev

访问地址: http://localhost:8500/

 

SpringCloud  整合 Consul

1 导入pom文件

<!--SpringCloud consul-server 注册中心consul-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>

2 编写yml文件

spring:
  application:
    name: cloud-consumer-order
  cloud:
    consul:
      # consul注册中心地址
      host: localhost
      port: 8500
      discovery:
        hostname: 127.0.0.1
        service-name: ${spring.application.name}

3 开启注解:

@EnableDiscoveryClient
package com.shi.order;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class OrderApplication {

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

4 .使用RestTemplat 进行测试

package com.shi.order.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ConfigApplication {

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

5. Controller测试调用

package com.shi.order.controller;

import com.shi.order.entity.CommonResoult;
import com.shi.order.entity.Payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class OrderController {

    private static String preUrl = "http://cloud-payment-service";

    @Autowired
    private RestTemplate restTemplate;

 
    @RequestMapping("/consumer/getPort")
    public CommonResoult<String> getPort(){
        CommonResoult<String> resoult = restTemplate.postForObject(preUrl + "/product/getPort",null,CommonResoult.class);
        return resoult;
    }

}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部