openFeign 访问别人的http,并附带token,可以定时去访问接口

时间:2022-12-26 09:56:32

1、导入依赖

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

2、编写配置类

我这里配置类包括FeignConfig和实体的配置类

PhotovoltFeignConfig: 日志level 和 请求拦截器
PhotovoltConfig: yml配置文件的信息

@Configurable
@Slf4j
public class PhotovoltFeignConfig implements RequestInterceptor {

    public static String token;


/*    @Bean
    public RequestInterceptor requestInterceptor() {
        System.out.println("n1");
        return requestTemplate -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (null != attributes) {
                HttpServletRequest request = attributes.getRequest();
                log.info("Feign request: {}", request.getRequestURI());
                // 将token信息放入header中
                System.out.println(token);
                requestTemplate.header("token",token);
            }
        };
    }*/

    @Bean
    Logger.Level photovoltFeignLevel(){
        //这里记录所有,根据实际情况选择合适的日志level
        return Logger.Level.FULL;
    }

    //请求头携带token
    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header("token", token);
    }
}
@Data
@Component
@ConfigurationProperties(prefix = "photovolt")
public class PhotovoltConfig {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty("地址")
    private String url;

    @ApiModelProperty("协议版本号")
    private String version;

    @ApiModelProperty("用户名")
    private String username;

    @ApiModelProperty("密码")
    private String password;

}

3、开启FeignClients

我这里自定义了一个开启FeignClients的注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EnableFeignClients(basePackages = {"com.cspg.photovolt.api"})
@Import({PhotovoltFeignConfig.class,PhotovoltConfig.class})
public @interface EnablePhotovoltFeignClients {
}

然后添加这个注解到启动类里

@SpringBootApplication
@Slf4j
@MapperScan("com.cspg.photovolt.mapper")
@EnablePhotovoltFeignClients
//定时任务
@EnableScheduling
public class PhotovoltApplication {

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

4、编写客户端调用别人提供的http接口

@FeignClient 标注该类是一个feign接口
name:因为这里并未进行服务注册,所以就随便命名一个
url:服务提供方的接口地址 (别人提供的http接口地址)

@FeignClient(name = "photovolt",url = "${photovolt.url}")
@Component
public interface PhotovoltApi {
    /**
     * 4.2.1 建立连接
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/login")
    JSONObject login(@RequestBody JSONObject jsonObject);

    /**
     * 4.3.3  获取配置
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/config_get")
    JSONObject getConfig(@RequestBody JSONObject jsonObject);

    /**
     * 4.4.1  在线数据拉取
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/online_data_get")
    JSONObject getOnlineData(@RequestBody JSONObject jsonObject);
}

5、调用服务端然后我们提供端接口

@RestController
@RequiredArgsConstructor
public class PhotovoltController {

    private final PhotovoltApi photovoltApi;

    private final PhotovoltConfig photovoltConfig;

    @Autowired
    private  PvTelemeterStatusService pvTelemeterService;


    @PostMapping(value = "/north/login")
    @PostConstruct
    @ApiOperation("4.2.1 建立连接")
    @Scheduled(cron = "0/2 * * * * ? ")
    public String login() {
        PhotovoltRequest photovoltResult = new PhotovoltRequest();
        JSONObject loginInfo = photovoltApi.login(photovoltResult.tologinJson());
        System.out.println(loginInfo);
        String error_msg = String.valueOf(loginInfo.get("error_msg"));
        String token = error_msg.substring(error_msg.indexOf(":") + 1);
        PhotovoltFeignConfig.token = token;
        return token;
    }

}

定时任务

上面已经写了,什么??????
没错就那两个注解

//定时任务
@EnableScheduling

//每2秒执行一次那个方法
@Scheduled(cron = "0/2 * * * * ? ")

最后

注意: 我这里并没有向其他文章一样自己搞个服务端的Controller,因为那个服务的接口地址是别人厂家弄好的了,我拿来用就行,只需在@FeignClient里指明url,然后在每个方法里指明下地址即可,然后在编写一个Controller去调用它获取返回结果