springboot中给restTemplate自定义过期时间

本文介绍如何在Spring项目中配置并使用多个RestTemplate实例的方法,通过自定义注解实现不同接口调用时选择合适的RestTemplate实例,同时展示了如何设置连接及读取超时等参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.配置restTemplate,因为我的项目已经存在restTemplate的配置,新的restTemplate是给一部分rest接口调用时使用的,所以自建一个注解@RestType来区分使用的哪一个:

@Configuration
public class RestConfig {

    @Bean
    @Primary
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Bean
    @RestType
    public RestTemplate restTemplateWithExpire(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //连接超时
        factory.setConnectTimeout(5);
        //连接成功后等待返回的超时
        factory.setReadTimeout(3000);
        return new RestTemplate(factory);
    }
}


//注解
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RestType {
}

2.用restTemplate调接口,用@RestType区分restTemplate实例

@Slf4j
@RestController
public class DemoController {

    @Resource
    @RestType
    private RestTemplate restTemplateWithExpire;

    @GetMapping("/test_rest_template_with_expire")
    public String testRestTemplateWithExpire(){
        String object = null;
        try {
//另起一个项目,随便写个接口运行
            object = restTemplateWithExpire.getForObject("http://127.0.0.1:9091/test_hello_with_expire", String.class);
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return "result is : " + object;
    }
}

 

### 实现 Spring Boot 项目中的企业微信消息通知 为了在 Spring Boot 项目中集成企业微信 API 并实现消息推送,需遵循特定配置与编码实践。 #### 创建并配置企业微信应用 创建新的企业微信应用时,应记录下 AppID 和 Secret 这两个重要参数[^1]。这些信息用于后续的身份验证过程。确保应用程序已启用,并设置回调URL以便接收来自企业微信服务器的通知。 #### 添加依赖项到 `pom.xml` 文件 为了让 Spring Boot 支持 HTTP 请求操作以及 JSON 数据处理等功能,在项目的 Maven 构建文件 pom.xml 中加入必要的库支持: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 如果需要JSON解析 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> ``` #### 获取 Access Token 访问企业微信接口前,先通过AppID和Secret向指定地址发起GET请求来换取access_token令牌。此token有效期为7200秒(即两小时),因此建议缓存该值并在过期前提前刷新它。 ```java public String getAccessToken(String corpId, String secret){ RestTemplate restTemplate = new RestTemplate(); String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpId+"&corpsecret="+secret; ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody()); return jsonObject.getString("access_token"); } ``` #### 发送消息给用户或群聊 定义一个方法用来构建POST请求体并将之发送至目标聊天对象。这里可以自定义消息类型(如文本、图片等),同时注意调整相应的字段以适应不同需求。 ```java public void sendMessageToUserOrChat(String accessToken, String toUserId, String content){ Map<String,Object> map=new HashMap<>(); map.put("touser",toUserId); // 接收者userid列表 map.put("msgtype","text"); // 消息类型设为文字形式 Map<String,String> textMap=Maps.newHashMap(); textMap.put("content",content); map.put("text",textMap); HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); HttpEntity<Map<String,Object>> formEntity = new HttpEntity<>(map,headers); RestTemplate restTemplate = new RestTemplate(); String postUrl="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken; ResponseEntity<String> responseEntity = restTemplate.postForEntity(postUrl,formEntity ,String.class ); } ``` 以上代码片段展示了如何利用 Java 编程语言配合 Spring Framework 的工具类完成对企业微信API调用的过程。值得注意的是,具体业务场景可能还会涉及到更多细节上的考量,比如错误重试机制的设计或是并发性能优化等方面的工作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值