立足于SpringCloud.H + consul-discovery + feign服务发现(19)

原创
01/06 19:11
阅读数 272

    《SpringCloud.H心法总纲》  

      继续上一篇,新建子模块consul-consumer服务发现,对服务注册模块consul-provider调用。

1、创建子模块consul-consumer

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

继承父模块daddy,修改pom

<parent>
    <groupId>com.springcloud</groupId>
    <artifactId>daddy</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</parent>

daddy修改pom对子模块consul-consumer的依赖

<module>consul-consumer</module>

2、application.properties

server.port=8066
spring.application.name=consul-consumer

spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
# 设置不需要注册到consul中
spring.cloud.consul.discovery.register=false

3、open-feign调用

@FeignClient(value = "consul-provider")
public interface MyFeign {

    @GetMapping(value = "/hi")
    String hi(@RequestParam("name") String name);
}
@Component
public class ComsuerService implements MyFeign {

    public String hi(String name){
        return "调用异常";
    }
}

4、controller层

@RestController
public class ConsumerController {
    
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    MyFeign myFeign;

    /**
     * 获取所有服务
     */
    @GetMapping("/services")
    public Object services() {
        return discoveryClient.getInstances("consul-provider");
    }

    @GetMapping(value = "/hi")
    public String sayHi(String name){
        return myFeign.hi(name);
    }
}

5、启动类

添加以下注解

@EnableFeignClients

6、测试

consul服务器运行,启动consul-provider模块,在启动consul-consumer子模块,调用consul-consumer的hi接口

成功运行,配置成功,实现了consul-comsuer的发现服务功能。

 

 

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