第 22 将 Spring集成RestTemplate消费消息

本文详细介绍如何在Spring中集成RestTemplate以消费HTTP服务。通过引入相关依赖并配置RestTemplate,实现对特定URL的GET请求,获取并打印返回的随机JSON字符串。此教程适用于希望在Spring应用中集成外部HTTP服务的开发者。

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

第二十二将 Spring集成RestTemplate消费消息

1.前言

这里主要介绍怎么使用RestTemplate去消费一个服务:http://gturnquist-quoters.cfapps.io/api/random.如果消费成功,会返回一个随机的Json字符串。

2.Spring集成RedisTemplate

2.1 引入依赖:pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2.2 配置RestTemplate:

package com.springboot.resttemplate.config;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @Description:
 * @Author: zrblog
 * @CreateTime: 2018-10-18 22:57
 * @Version:v1.0
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}

2.3 测试:Application

package com.springboot.resttemplate;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class Application {

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

	@Bean
	public CommandLineRunner run(RestTemplate restTemplate) {
		return args -> {
            String resultStr = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", String.class);
            System.out.println(resultStr);
        };
	}

}

  • 测试结果:

a

参考资料:用restTemplate消费服务

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值