SpringCloud 之OpenFeign 自定义配置和使用/自定义拦截器

什么是Feign

Feign 是一个声明性的 Web 服务客户端。它使编写 Web 服务客户端变得更加容易。要使用Feign,请创建一个界面并对其进行注释。它具有可插入的注释支持,包括假装注释和 JAX-RS 注释。Feign 还支持可插拔编码器和解码器。春云增加了对弹簧MVC注释的支持,以及使用春季网页中默认使用的相同Http消息转换器的支持。弹簧云集成了尤里卡,弹簧云断路器,以及弹簧云负载平衡器,以便在使用Feign时提供负载平衡的http客户端。
Spring Cloud Open Feign对Feign进行了增强,使其支持Spring MVC注解,另外还整合了Ribbon和Nacos,从而使得Feign更加方便.

1.引入依赖

     <!--      spring-cloud-dependencies      -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR12</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
       <!-- 微服务调用     -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

Feign接口案例

1.创建一个Feign接口

/**
 * 创建一个接口加上@FeignClient注解,声明这是一个Feign接口
 * name :指定调用rest接口所对应的服务名
 * path :指定调用的rest接口所在Controller指定的统一映射路径(一般很少用,因为可能多个方法调用的是不同的Controller的接口,可以直接在方法上指定接口的映射路径)
 */
@FeignClient(name= "manage-client")
public interface UserFeignServuce {

    @RequestMapping(value = "/index/test")
    String  test(String name);
}

2.注入feign接口,在消费端只需要像使用普通的方法一样,通过**@Autowired**注解注入接口,并调用传参就可以了


    @Autowired
    UserFeignServuce userFeignServuce;

    @RequestMapping(value = "/test",method = RequestMethod.POST)
    private CommonResult test(){
        String name = "OK";
        String key = userFeignServuce.test(name);
        return new CommonResult(key );
    }

3.开启feign
添加 @EnableFeignClients 注解

@SpringBootApplication
@EnableFeignClients    //开启Feign
public class ManageApplication {
    public static void main(String[] args) {
        SpringApplication.run(ManageApplication.class,args);
    }
}

OpenFeign的自定义配置和使用

日志配置
4种日志基本
NONE, 不记录(默认)。
BASIC, 只记录请求方法和 URL 以及响应状态码和执行时间。
HEADERS, 记录基本信息以及请求和响应标头。
FULL, 记录请求和响应的标头、正文和元数据。
全局配置
定义一个配置类,指定日志级别

//加@Configuration注解为全局配置
@Configuration
public class FooConfiguration {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

指定feign全局的日志级别

#SpringBoot默认的日志基本是info,feign的debug日志级别就不会输出
logging:
  level:
    #feign接口的包路径
    com.saas.manage.feign: debug

局部配置

feign:
  client:
    config:
      #需要配置的服务名称
      manage-client:
        #设置日志级别
        loggerLevel: FULL
        #契约配置  一般情况下是不会使用的  由于openFeign 是对 Feign的增强在Spring Cloud 1 里面有独立的一套注解,在Netflix闭源后,SpringCloud才切换到了Openfeign并支持Spring注解,如果在老项母使用Cloud 1架构的项目中是用了feign的原生注解,需要升级可下面的配置进行还原 例如:在feign原生注解中 @requestLine 来对应 @RequestMapping 
#       contract: feign.Contract.Default #设置为默认的契约 (还原成原生注解)

超时时间配置
配置类方式

@Configuration
public class FooConfiguration {
    //超时时间配置
    @Bean
    public Request.Options options() {
        return new Request.Options(5000,10000);
    }
}

yml配置

feign:
    client:
        config:
            feignName:
                #防止由于服务器处理时间长而阻塞调用者
                connectTimeout: 5000
                #从连接建立时开始应用,在返回响应时间过长时触发
                readTimeout: 5000

feign组件自定义拦截器

自定义一个拦截器并实现 RequestInterceptor 接口

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

/**
 * feign拦截器
 */
@Slf4j
public class CustomFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //TODO  根据需求可以在拦截器中扩展需要的功能
        log.info("比如记录日志 /增加参数 / 修改路径 / 鉴权");
    }
}

源码

在这里插入图片描述
配置方式1 注入bean

    @Bean
    public CustomFeignInterceptor customFeignInterceptor(){
        return new CustomFeignInterceptor();
    }

配置方式2yaml

#开启sentinel对feign组件远程调用服务降级的支持
feign:
  client:
    config:
      #需要配置的服务名称
      manage-client:
        loggerLevel: FULL
        #连接超时时间,默认2s
        connectTimeout: 5000
        #请求处理超时时间,默认5a
        readTimeout: 10000
        #拦截器配置
        requestInterceptors[0]: com.car.hailing.saas.manage.feign.intercptor.CustomFeignInterceptor

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在 Spring Boot 中使用 shiro 配置自定义过滤器需要以下几个步骤: 1. 引入 shiro-spring-boot-starter 依赖: ``` <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-starter</artifactId> <version>1.7.1</version> </dependency> ``` 2. 创建自定义过滤器: ``` public class CustomFilter extends AccessControlFilter { @Override protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception { // 在这里实现自定义的过滤逻辑,返回 true 表示通过过滤器,返回 false 表示未通过过滤器 return true; } @Override protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { // 如果 isAccessAllowed 返回 false,则会进入到这里,可以在这里处理未通过过滤器的情况 return false; } } ``` 3. 配置 shiro 的 FilterChainDefinition: ``` @Bean public ShiroFilterChainDefinition shiroFilterChainDefinition() { DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition(); // 添加自定义过滤器,其中 key 是过滤器名称,value 是该过滤器对应的路径 chainDefinition.addPathDefinition("/custom/**", "custom"); return chainDefinition; } ``` 4. 配置自定义过滤器: ``` @Bean("custom") public CustomFilter customFilter() { return new CustomFilter(); } ``` 5. 配置 shiro 的注解支持: ``` @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) { AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); advisor.setSecurityManager(securityManager); return advisor; } ``` 完成以上步骤后,就可以在 Spring Boot 中使用 shiro 配置自定义过滤器了。 ### 回答2: 在 Spring Boot 中使用 Shiro 配置自定义过滤器分为三个步骤。 第一步,创建自定义过滤器类。可以通过实现 Shiro 的 Filter 接口来创建自定义过滤器。在自定义过滤器中需要实现过滤规则,并对请求进行相应的处理。 第二步,配置 Shiro 过滤器链。在 Spring Boot 的配置类中,通过创建 ShiroFilterFactoryBean 对象来配置 Shiro 的过滤器链。可以使用 Shiro 的 FilterChainDefinitionMap 对象来配置过滤器链,然后将该对象设置给 ShiroFilterFactoryBean。 第三步,启用 Shiro 过滤器。在 Spring Boot 的配置类中,通过创建 DefaultFilterChainManager 对象,并将该对象设置给 ShiroFilterFactoryBean,启用自定义过滤器。 有了以上三步,就可以在 Spring Boot 中使用 Shiro 配置自定义过滤器了。可以通过在自定义过滤器中实现过滤规则来对请求进行拦截或处理,然后在 Shiro 过滤器链中配置该过滤器,最后启用该过滤器。这样就可以实现对请求的自定义过滤器处理。 值得注意的是,在使用 Shiro 进行自定义过滤器配置时,需要保证 Shiro 的配置文件中已经进行了相应的配置,包括认证和授权等相关配置。只有在正确配置的前提下,才能正确使用 Shiro 进行自定义过滤器的配置。 ### 回答3: 在Spring Boot中使用Shiro配置自定义过滤器通常需要以下几个步骤: 1. 引入Shiro和Spring Boot依赖。在pom.xml文件中添加Shiro和Spring Boot Starter依赖: ``` <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-starter</artifactId> <version>1.7.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. 创建自定义过滤器类。可以通过实现`javax.servlet.Filter`接口或者继承`org.apache.shiro.web.servlet.OncePerRequestFilter`类来创建自定义过滤器。例如,创建一个名为`CustomFilter`的自定义过滤器类: ``` public class CustomFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 过滤器逻辑处理 // ... filterChain.doFilter(request, response); } } ``` 3. 在Shiro配置类中注册自定义过滤器。创建一个Shiro配置类,并使用`@Configuration`注解标记为配置类。通过`@Bean`注解将自定义过滤器注册到Shiro的过滤器链中。例如,在配置类`ShiroConfig`中注册`CustomFilter`: ``` @Configuration public class ShiroConfig { @Bean public FilterRegistrationBean<CustomFilter> customFilterRegistrationBean() { FilterRegistrationBean<CustomFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new CustomFilter()); registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); // 过滤器执行顺序 registrationBean.addUrlPatterns("/*"); // 过滤器路径 return registrationBean; } } ``` 4. 配置Shiro的过滤规则。在Shiro配置文件中,可以设置自定义过滤器的拦截规则。例如,在`shiro.ini`配置文件中,设置自定义过滤器的拦截规则: ``` [urls] /** = customFilter // 对所有请求都使用自定义过滤器 ``` 通过以上步骤,在Spring Boot中使用Shiro配置自定义过滤器就可以实现对特定请求的拦截和处理。在`CustomFilter`类的`doFilterInternal`方法中编写自定义的过滤器逻辑,例如鉴权、权限验证等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值