Feign入门实例

1.先创建一个工程,引用maven控制 ,比着之前的消费者的项目增加了一个feign的依赖

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

2.第二步、在启动类上增加@EnableFeignClients和@EnableEurekaClient 注解,@EnableFeignClients注解是启用了feign客户端,如果Feign接口与启动类不是在同一个包下,需要增加包的扫描,@EnableFeignClients(basePackages=“com.ssc.demo”)

package com.ssc.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients
public class DemoApplication {

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

}

 

3.第三步,创建Feign接口

package com.ssc.demo;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
//@FeignClient注解,这个注解标识当前是一个 Feign 的客户端,value 属性是对应的服务名称,也就是你需要调用哪个服务中的接口。
@FeignClient(value = "eureka-user-provide",fallbackFactory = SysUserClinetFallbackFactory.class)
public interface UserRemoteClient {
//这个位置的请求路径就是,在这个提供者实例下提供具体服务的路径
    @RequestMapping(value = "/user/hello",method = RequestMethod.GET)
    String hello();
}

@Slf4j
@Component
public class SysUserClinetFallbackFactory implements FallbackFactory<SysUserClient> {

    @Override
    public SysUserClient create(Throwable throwable) {
        return new UserRemoteClient(){
            @Override
            public LoginUser hello() {
                log.error("调用{}异常:{}");
                throwable.printStackTrace();
                return null;
            }

        };
    }
}

4.第四步,写消费者调用类

package com.ssc.demo;

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

@RestController
public class CallHello {

    @Autowired
    private UserRemoteClient userRemoteClient;
    @GetMapping(value = "/callHello")
    public String calloHello(){

//此时的调用相当于 http://eureka-user-provide/user/hello
        String result=userRemoteClient.hello();
        System.out.println("调用结果:"+result);
        return result;
    }
}

5.第五步,书写yml配置文件

server:
  port: 8099
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
  instance:
    instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
spring:
  application:
    name: feign-user-consumer

6.第六步启动应用,调用接口。先查看eureka注册中心

输入请求路径,查看http://127.0.0.1:8099/callHello,成功调用

 

posted @ 2023-03-15 14:40  司徒翘臀  阅读(95)  评论(0)    收藏  举报