63、SpringBoot---定制 RestTemplate--消息转化器、拦截器

★ 定制RestTemplate

复制代码
如要对RestTemplate进行自定义设置,Spring Boot也提供了两种主要方式:

▲ 局部式:在调用RestTemplateBuilder构建RestTemplate之前,先调用RestTemplateBuilder的方法对其定制,

   通过这种方式设置的RestTemplateBuilder仅对它构建的RestTemplate起作用。

▲ 全局式:使用RestTemplateCustomizer进行定制,所有实现RestTemplateCustomizer接口
   的Bean会被自动应用到自动配置的RestTemplateBuilder中,这种定制方式对整个应用范围的RestTemplate都起作用。

之前这个就属于局部式定制:

★ 定制RestTemplate主要在如下两方面进行定制:

复制代码
▲ 添加或替换拦截器:既可通过 RestTemplateBuilder 的 additionalInterceptors() 或 interceptors() 方法分别添加或替换拦截器。
   也可直接调用RestTemplate的方法来添加或替换。

▲ 添加或替换消息转换器:既可通过 RestTemplateBuilder 的 additionalMessageConverters() 或   messageConverters() 方法分别添加或替换拦截器。
   也可直接调用RestTemplate的方法来添加或替换。

全局式定制RestTemplate的代码演示

延用--SpringBoot 使用RestTemplate 整合第三方 RESTful 服务--的代码

全局式定制RestTemplate,创建一个 ClientCustomizer 类,实现 RestTemplateCustomizer 接口

测试:

可以看出 定制的 RestTemplate 的拦截器生效,开始执行。

java 复制代码
package cn.ljh.app.controller;


import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.List;

//定制 RestTemplate

@Slf4j
@Configuration
public class ClientCustomizer implements RestTemplateCustomizer
{

    @Override
    public void customize(RestTemplate restTemplate)
    {
        //在此处即可对容器中自动构建的所有 RestTemplate 进行全局配置
        //添加HttpMessageConverters消息转换器,先get获取到所有消息转换,然后再用 add 进行添加
        FastJsonHttpMessageConverter messageConverter = new FastJsonHttpMessageConverter();
        //该设置说明FastJsonHttpMessageConverter只处理Json格式的数据
        messageConverter.setSupportedMediaTypes(List.of(MediaType.APPLICATION_JSON));
        //这样就添加了自定义的定制的消息转换器-----对象和json之间的转换
        restTemplate.getMessageConverters().add(messageConverter);

        //替换原有的拦截器
        //restTemplate.setInterceptors(List.of());
        //在原有的拦截器的基础上再添加自己的拦截器
        //此处可以用 Lambda 表达式来创建拦截器
        restTemplate.getInterceptors().add((request, body, execution) ->
        {
            //在这里面自定义拦截器规则
            log.debug("RestTemplate 的拦截器开始执行");
            String url = request.getURI().getPath();
            //设置token半小时内有效
            int time = (int) (System.currentTimeMillis() / 1000 + 1800);
            //获取请求方法名
            String methodName = request.getMethod().name();
            //获取请求体数据
            String strBody = new String(body);
            //此处调用服务器的方法来生成token,生成的token需要哪些参数,取决于服务器
            String token = generateToken(url, time, methodName, strBody);
            //设置一个额外的请求头(常常需要再授权时要设置额外的请求头)
            //具体要添加什么请求头,取决于业务的需要。
            request.getHeaders().add("X-cn-ljh", token);
            //继续向下执行
            return execution.execute(request, body);
        });
    }
    //模拟生成token
    private String generateToken(String url, int time, String method, String strBody)
    {
        return "mycustomtoken";
    }
}

pom.xml

需要这个fastjson 依赖,用于添加HttpMessageConverters消息转换器

相关推荐
兔兔爱学习兔兔爱学习31 分钟前
Spring Al学习7:ImageModel
java·学习·spring
lang201509282 小时前
Spring远程调用与Web服务全解析
java·前端·spring
m0_564264182 小时前
IDEA DEBUG调试时如何获取 MyBatis-Plus 动态拼接的 SQL?
java·数据库·spring boot·sql·mybatis·debug·mybatis-plus
崎岖Qiu2 小时前
【设计模式笔记06】:单一职责原则
java·笔记·设计模式·单一职责原则
Hello.Reader3 小时前
Flink ExecutionConfig 实战并行度、序列化、对象重用与全局参数
java·大数据·flink
熊小猿3 小时前
在 Spring Boot 项目中使用分页插件的两种常见方式
java·spring boot·后端
paopaokaka_luck4 小时前
基于SpringBoot+Vue的助农扶贫平台(AI问答、WebSocket实时聊天、快递物流API、协同过滤算法、Echarts图形化分析、分享链接到微博)
java·vue.js·spring boot·后端·websocket·spring
老华带你飞4 小时前
机器人信息|基于Springboot的机器人门户展示系统设计与实现(源码+数据库+文档)
java·数据库·spring boot·机器人·论文·毕设·机器人门户展示系统
notion20254 小时前
Adobe Lightroom Classic下载与安装教程(附安装包) 2025最新版详细图文安装教程
java·数据库·其他·adobe
rengang664 小时前
351-Spring AI Alibaba Dashscope 多模型示例
java·人工智能·spring·多模态·spring ai·ai应用编程