美文网首页
springCloud 集成feign

springCloud 集成feign

作者: 无我_无他_有你 | 来源:发表于2022-02-23 16:17 被阅读0次

    以A(消费者)服务远程调用B(生产者)服务为例

    1. A,B服务引入依赖

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

    2.A,B服务启动类上添加@EnableFeignClients注解开启Spring Cloud Feign的远程支持功能

    /**
     * 类说明:
     *
     * @author wqf
     * @date 2021/7/9 17:54
     */
    @EnableFeignClients(basePackages = {"pers.darcy.flower.gateway.service.feign.api"})
    @SpringBootApplication
    public class GatewayServiceApplication {
        public static void main(String[] args) {
            SpringApplication.run(GatewayServiceApplication.class);
        }
    
        //处理feign远程调用报错:No qualifying bean of type ‘org.springframework.boot.autoconfigure.http.HttpMessage...
        @Bean
        @ConditionalOnMissingBean
        public HttpMessageConverters messageConverters(ObjectProvider<HttpMessageConverter<?>> converters) {
            return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList()));
        }
    }
    

    3.A服务编写远程调用接口

    @FeignClient(value = "account-server", fallback = AuthPermissionFeignBack.class)
    public interface AuthPermissionFeignApi {
    
        /**
         * 方法描述: 查询用户id
         *
         * @param userId 用户id
         * @return java.util.List<pers.darcy.flower.account.api.dto.PermissionDTO>
         * @author wqf
         * @date 2022/2/22 14:04
         */
        @GetMapping(value = "/user/permissions/{userId}")
        List<PermissionDTO> listUserPermissions(@PathVariable("userId") Long userId);
    }
    

    说明:

    1. account-server B服务名称(被调用方服务名称 spring.application.name)
      接口上添加注解:@FeignClient
    2. fallback = AuthPermissionFeignBack.class 表示方法的降级,当该接口方法出现错误,将会走AuthPermissionFeignBack类中的实现
    3. @PathVariable("userId") 不可以写成@PathVariable,就算参数名和接口中的一样, 否则会报错
    4. @GetMapping(value = "/user/permissions/{userId}") 接口路径和B服务的接口路径保持一致

    AuthPermissionFeignBack.java

    @Slf4j
    public class AuthPermissionFeignBack implements AuthPermissionFeignApi {
        @Override
        public List<PermissionDTO> listUserPermissions(Long userId) {
            log.info("-----服务降级-----");
            return null;
        }
    }
    

    4.B 写接口

    @Slf4j
    @RestController
    @RequestMapping(value = "/user")
    public class UserController {
        @GetMapping(value = "/permissions/{userId}")
        public List<PermissionDTO> listUserPermissions(@PathVariable Long userId) {
            PermissionDTO permissionDTO = new PermissionDTO();
            permissionDTO.setId(1L);
            return Collections.singletonList(permissionDTO);
        }
    }
    

    以上应该就可以了

    相关文章

      网友评论

          本文标题:springCloud 集成feign

          本文链接:https://www.haomeiwen.com/subject/dxjglrtx.html