SpringCloud服务调取feign(配合Eureka)

SpringCloud服务调取feign(配合Eureka)

需要先完成eureka服务搭建->Eureka服务搭建

  • maven依赖

    org.springframework.cloud
    spring-cloud-starter-openfeign
    2.2.2.RELEASE
  • 启动类配置
  • @EnableDiscoveryClient 
    @EnableFeignClients 支持feign的服务标签
  • @EnableEurekaClient
    @SpringBootApplication 如果只是调用eureka注册中心服务 , 自身不提供服务则不需要引入eureka依赖和相关配置,这两个标签也是不需要的
package com.ll;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableDiscoveryClient 
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class JobApplication extends SpringBootServletInitializer{

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

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources( JobApplication.class );
	}
}
  • yaml用默认配置即可,这里没有做任何自定义配置
  • 提供feign调用
package com.ll.job.feign;

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

@Component
@FeignClient(name = "ll-job")
public interface FeignService {


    @GetMapping(value = "/job/job/findAllDictionary")
    String findAllDictionary();

    @GetMapping(value = "/job/job/getJob")
    String getJob(@RequestParam String id);
}
  • @FeignClient :注解 , 给的是注册在eureka的名称

SpringCloud服务调取feign(配合Eureka)_第1张图片

  •  调用时直接引入对象调用即可,注入建议这样注入
  • 例如:feignService.findAllDictionary();
//feign 接口注入方式
private FeignService feignService;

@Autowired
public void setFeignService(FeignService feignService) {
    this.feignService = feignService;
}

chenyb 随笔记录,只为方便自己学习

2020-07-27

你可能感兴趣的:(Spring,Spring,Cloud,SpringBoot)