SpringBoot Feign接口方式調用服務


1、前文接 SpringBoot Eureka集群配置

2、EurekaConsumer_Feign_9002

添加openfeign依賴

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

添加yml配置

eureka:
  client:
    register-with-eureka: false
    serviceUrl: #注冊中心的注冊地址
      defaultZone: http://127.0.0.1:7001/eureka/
server:
  port: 9002  #服務端口號
spring:
  application:
    name: service-consumer #服務名稱--調用的時候根據名稱來調用該服務的方法

EurekaConsumer_Feign_9002啟動類添加@EnableFeignClients掃描包

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

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.kikyo"})
public class EurekaConsumer_Feign_9002 {
    public static void main(String[] args) {
        SpringApplication.run(EurekaConsumer_Feign_9002.class, args);
    }
}

TestService這個接口是從Eureka服務(SERVICE-PROVIDER)拿實現類的

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

@Component
@FeignClient("SERVICE-PROVIDER")
public interface TestService {
    @GetMapping("/get")
    String get();
}

接收請求

import com.kikyo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class TestController {
    @Autowired
    private TestService testService = null;

    @RequestMapping("/get")
    public String getUser() {
        return testService.get();
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM