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消息转换器

相关推荐
Spatial3Ddddd3 小时前
2026空间三维重建服务商横向对比
java·服务器·人工智能
Rain的Java大神之路3 小时前
Java 三层架构,90% 的人只答对一半:Controller 不是瘦,Service 不是透传,Dao 不是只写 SQL
java·后端·面试
Thomas.Sir3 小时前
第29课:微服务异步调用、线程池优化 & 事件驱动开发
java·redis·微服务
.Hypocritical.3 小时前
【Java 进阶】泛型深度解析|泛型类、泛型方法、通配符、类型擦除、PECS 原则
java·开发语言·泛型
这个DBA有点耶3 小时前
MySQL B-tree索引并发控制优化:写密集场景的锁瓶颈与内核级解法
java·数据库·程序人生·算法·database·dba
小羊没烦恼!4 小时前
浅谈SQL Server中的事务日志(二)----事务日志在修改数据时的角色
前端·数据库·后端·python·web安全·oracle
RuoyiOffice4 小时前
Spring AI+Vue3 企业知识库设计:让每个答案有依据,让每份资料守住权限
java·spring boot·vue3·rag·企业知识库·spring ai·ruoyi office
IT_陈寒4 小时前
一文搞懂Vite的核心概念
前端·人工智能·后端
一个简单的TTS开发者4 小时前
中文TTS工具有哪些-8款主流方案横向对比
人工智能·后端·python·indextts
倔强的石头1064 小时前
【Linux指南】进程通信系列(二):匿名管道 —— pipe 的本质、fork 继承与四种读写规则
java·linux·运维