JavaEE:SpringCloud-使用Feign调用微服务

一、导入SpringCloud与SpringBoot依赖包(必须版本对应,此处为2.2.x <-> Hoxton):

见此文章第一章:https://blog.csdn.net/a526001650a/article/details/106859559

二、给被调用Module中配置微服务名称,在被调用Module工程/application.yml文件中:

spring:
  application:
    name: mall-usercenter #配置被调用微服务的名称

三、使用Feign调用微服务(在调用者Module中配置):

1.导入Feign依赖包、Eureka的Client端依赖包、Web功能依赖包:


    
    
        org.springframework.cloud
        spring-cloud-starter-openfeign
    
    
    
        org.springframework.cloud
        spring-cloud-starter-netflix-eureka-client
    
    
    
        org.springframework.boot
        spring-boot-starter-web
    

2.导入Eureka Server配置的地址,否则无法发现服务:

spring:
  application:
    name: mall-feign #配置当前微服务名称
server: #配置当前微服务端口号
  port: 10002

eureka: #导入Eureka Server配置的地址,否则无法发现服务
  client:
    service-url:
      defaultZone: http://127.0.0.1:10000/eureka/

3.在Application启动类上添加Feign注解:

@SpringBootApplication //标识为启动类
@EnableDiscoveryClient //发现微服务
@EnableFeignClients    //用Feign方式调用
public class FeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignApplication.class);//加载启动类
    }
}

4.添加Feign调用接口(调用配置了EurekaClient端的微服务Module):

@FeignClient("mall-usercenter") //配置被调用的微服务名称(不能有下划线)
public interface UserCenterClient {
    //请求路径为:http://127.0.0.1:10001/getUserDetail/xxx ,userNo是参数值
    @RequestMapping(value = "getUserDetail/{userNo}", method = RequestMethod.GET)
    String getUserDetail(@PathVariable("userNo") String userNo); // @PathVariable用于将{userNo}的值取出,赋值给userNo
}

5.测试调用,创建请求处理类:

@Controller
public class UserAPIController {
    @Autowired
    private UserCenterClient uerCenterClient;
    //请求路径:http://127.0.0.1:10002/getUserDetailAPI/1001,userNo是参数值
    @RequestMapping(value = "getUserDetailAPI/{userNo}", method = RequestMethod.GET)
    @ResponseBody // @ResponseBody将返回对象转换为json字符串
    public String getUserDetailAPI(@PathVariable("userNo") String userNo) {// @PathVariable用于将{userNo}的值取出,赋值给userNo
        String json = uerCenterClient.getUserDetail(userNo);
        System.out.println("从用户中心微服务获取的值, json: " + json);
        return json;
    }
}

四、配置Hystrix熔断器(A微服务 -> B微服务 -> C微服务,B微服务出问题时,A微服务还能正常使用)(在调用者Module中配置):

1.打开Hystrix熔断器,在调用者Module工程/application.yml文件中:

feign:
  hystrix: #打开Hystrix熔断器
    enabled: true

2.新增Feign调用接口的实现类:

//Hystrix熔断器实现,要加@Component组件扫描
@Component
public class UserCenterClientImpl implements UserCenterClient {
    @Override
    public String getUserDetail(String userNo) {
        return "触发Hystrix熔断器";
    }
}

3.在Feign调用接口中配置实现类(熔断器):

@FeignClient(value = "mall-usercenter", fallback = UserCenterClientImpl.class) //fallback配置实现类(熔断器)
public interface UserCenterClient {
    ...
}

 

你可能感兴趣的:(JavaEE)