【1.5】SpringCloud入门之Eureka consumer OpenFeign

让人想犯罪 __ 提交于 2020-12-24 01:42:22

用maven创建一个eureka-consumer-feign

1.引入springcloud对应的pom

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>2.2.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

2.新建启动类,服务调用类,请求入口类

2.1 EurekaConsumerFeignApplication 

package com.pimee;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients
@SpringBootApplication
public class EurekaConsumerFeignApplication {

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

2.2 HelloRemote

package com.pimee.service;

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

@FeignClient(name = "eureka-provider")
public interface HelloRemote {

    @GetMapping("/hello/{name}")
    String hello(@RequestParam(value = "name") String name);

}

2.3 HelloController

package com.pimee.controller;

import com.pimee.service.HelloRemote;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/hello")
@RestController
public class HelloController {

    @Autowired
    HelloRemote helloRemote;

    @GetMapping("/{name}")
    public String index(@PathVariable("name") String name) {
        return helloRemote.hello(name + "!");
    }

}

3.在resources下面添加application.yml

server:
  port: 8083
spring:
  application:
    name: eureka-consumer-feign
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

4.启动测试

调用成功,http://localhost:8083/hello/bobo

代码已放在gitee

https://gitee.com/pimee/springcloud-learn.git

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!