03-客户端调用(消费者)

参考:
http://www.ityouknow.com/springcloud/2017/05/12/eureka-provider-constomer.html

D:\springcloud\eureka-consumer

目标

  • 工程导入
  • pom.xml
  • 配置文件
  • 启动类
  • feign调用
  • web层调用远程服务
  • 测试

工程导入

拷贝刚才的工程eureka-service并改名为eureka-consumer

pom.xml

在生产者配置的基本上增加feign依赖

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

配置文件

spring.application.name=spring-cloud-consumer
server.port=9001
eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/

启动类

启动类添加@EnableDiscoveryClient和@EnableFeignClients注解。

@EnableDiscoveryClient //向服务中心注册;并且向程序ioc注入一个bean
@EnableFeignClients //开启feign的功能
@SpringBootApplication
public class DemoApplication {

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

feign调用实现

FeignClient配置参数中的name:远程服务名,及spring.application.name配置的名称
此类中的方法和远程服务中contoller中的方法名和参数需保持一致。

package com.example.demo.inter;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(name= "spring-cloud-producer")
public interface HelloRemote {
    @RequestMapping(value = "/hello")
    public String hello(@RequestParam(value = "name") String name);
}

web层调用远程服务

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.inter.HelloRemote;

@RestController
public class ConsumerController {
    @Autowired
    HelloRemote HelloRemote;
    
    @RequestMapping("/hello/{name}")
    public String index(@PathVariable("name") String name) {
        return HelloRemote.hello(name);
    }
}

到此,最简单的一个服务注册与调用的例子就完成了。

测试

1)依次启动spring-cloud-eureka、spring-cloud-producer、spring-cloud-consumer三个项目

2)先输入:http://localhost:9000/hello?name=neo 检查spring-cloud-producer服务是否正常

返回:hello neo,this is first messge


image.png

说明spring-cloud-producer正常启动,提供的服务也正常。

3)浏览器中输入:http://localhost:9001/hello/neo

返回:hello neo,this is first messge


image.png

说明客户端已经成功的通过feign调用了远程服务hello,并且将结果返回到了浏览器。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容