栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

SpringCloud-Feign接口转换服务

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringCloud-Feign接口转换服务

Feign是通过提供面向接口操作的方式来替代RestTemplate API的Rest操作。

使用Feign

Feign这种技术应用在服务消费端

  1. 修改pom.xml配置文件,加入Feign的依赖包


    org.springframework.cloud
    spring-cloud-starter-feign
  1. 由于Fegin是将Rest的操作转换成接口的形式,所以我们需要新建一个接口,并在接口上声明@FeignClient注解

@FeignClient(value = "DEPT-PROVIDER",configuration = FeignClientConfig.class)public interface DeptClientService {    @RequestMapping(method= RequestMethod.GET,value="/dept/get/{id}")    public Dept get(@PathVariable("id") long id) ;    @RequestMapping(method=RequestMethod.GET,value="/dept/list")    public List list() ;    @RequestMapping(method=RequestMethod.POST,value="/dept/add")    public boolean add(Dept dept) ;
}@Configurationpublic class FeignClientConfig {    @Bean
    public Logger.Level getFeignLoggerLevel() {        return feign.Logger.Level.FULL ;
    }    @Bean
    public BasicAuthRequestInterceptor getBasicAuthRequestInterceptor() {        return new BasicAuthRequestInterceptor("admin", "admin");
    }
}

其中configuration = FeignClientConfig.class不是必须的,将configuration属性去除仍然能work。

  1. 将之前的Rest操作的API,替换成面向DeptClientService接口的形式

@RestController@RequestMapping("/consumer/dept")public class ConsumerDeptController {    @Autowired
    private DeptClientService deptClientService;    @RequestMapping(value = "/get")    public Dept get(long id) {        return this.deptClientService.get(id);
    }    @RequestMapping("/list")    public List list(){        return this.deptClientService.list();
    }    @RequestMapping("/add")    public boolean add(Dept dept){        return this.add(dept);
    }}
  1. 在启动类中加入@EnableFeignClients注解

@SpringBootApplication@EnableEurekaClient@EnableFeignClients(basePackages = {"cn.zgc.service"})public class FeignConsumer_80_StartSpringCloudApplication {    public static void main(String[] args) {
        SpringApplication.run(FeignConsumer_80_StartSpringCloudApplication.class,args);
    }
}

Feign自带了负责均衡特性,所以使用Feign之后可以不用使用Ribbon。

Feign的配置

Feign 最重要的功能就是将 Rest 服务的信息转换为接口,但是在实际的使用之中也需要考虑到一些配置情况,例如:数据压缩, Rest 的核心本质在于: JSON 数据传输( XML、文本),于是就必须思考一种情况,万一用户发送的数据很大呢? 所以这个时候可以考虑修改application.yml 配置文件对传输数据进行压缩;

feign:
 compression:
 request:
 mime-types:  # 可以被压缩的类型
 - text/xml
 - application/xml
 - application/json
 min-request-size: 2048 # 超过2048的字节进行压缩

开启Feign的日志(默认是不开启的)

logging: level: cn.zgc.service: DEBUG



作者:Coding小聪
链接:https://www.jianshu.com/p/48ebe8ec5152

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/235644.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号