SpringCloud项目实例--服务通讯基础API方法

在这里插入图片描述

Spring Cloud Alibaba提供的组件如下:

Sentinel:阿里巴巴开源产品,不仅仅可以作为断路器,也支持流量控制和服务降级。
Nacos:阿里巴巴开源产品,服务注册与服务发现,同时也可以作为配置中心。
RocketMQ:阿里巴巴开源的分布式消息和流计算平台。
Dubbo:阿里巴巴开源产品,高性能Java RPC框架,服务通信组件。
Seata:阿里巴巴开源产品,一个易于使用的高性能微服务分布式事务解决方案。
Alibaba Cloud ACM:其前身为淘宝内部配置中心Diamond,是一款应用配置中心产品,需付费。
Alibaba Cloud OSS:阿里云对象存储OSS是一款海量、安全、低成本、高可靠的云存储服务,需付费。
Alibaba Cloud SMS:阿里云短信服务,需付费。
Alibaba Cloud SchedulerX:阿里中间件自研的基于Akka架构的新一代分布式任务调度平台,需付费。

lombok

在这里插入图片描述

服务通信基础实例

分别存放业务层实现类和REST层的Controller类。

service包中新建HelloServiceImpl类

package ltd.newbee.cloud.service;

import org.springframework.stereotype.Component;

@Component
public class HelloServiceImpl {

    public String getName(){
        return "service01";         //定义了getName()方法,方法作用是返回一个字符串。
    }                         
}

web包中新建HelloServiceController类,代码如下:

package ltd.newbee.cloud.web;

import ltd.newbee.cloud.service.HelloServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloServiceController {

    @Autowired
    private HelloServiceImpl helloService;

    @GetMapping("/hello")
    public String hello() {
        // 调用本地方法,并通过HTTP协议进行响应
        return "hello from " + helloService.getName();
    }
}

@RestController注解,所以并不会返回视图对象。类中定义了hello()方法,映射地址为/hello,在访问该地址后会返回一串字符串给调用端。

使用HttpClient处理请求

在pom.xml文件中添加httpclient的依赖配置,代码如下:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
</dependency>

创建ltd.newbee.cloud.web包,用于存放调用端所需的测试类。在web包中新建ConsumerController类,代码如下:

package ltd.newbee.cloud.web;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class ConsumerController {

    private final String SERVICE_URL = "http://localhost:8081";
    //private final String SERVICE_URL = "http://localhost:8082";

    /**
     * 使用HttpClient来处理http请求
     * @return
     * @throws IOException
     */
    @GetMapping("/httpClientTest")
    public String httpClientTest() throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(SERVICE_URL + "/hello");
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpGet);
            // 判断返回状态码
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                // 打印请求结果
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpClient.close();
        }
        return "请求成功";
    }
}

在这里插入图片描述

使用RestTemplate处理请求

RestTemplate是Spring提供的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,简化了在Java代码中处理http请求的编码过程。
首先,创建config包,并新建RestTemplate的配置类,代码如下:

package ltd.newbee.cloud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.converter.StringHttpMessageConverter;

import java.nio.charset.Charset;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        // UTF-8编码设置
        restTemplate.getMessageConverters().set(1,
                new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;

    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 超时时间 10秒
        factory.setReadTimeout(10 * 1000);
        // 超时时间 5秒
        factory.setConnectTimeout(5 * 1000);
        return factory;
    }
}

在ConsumerController类中引入RestTemplate对象,并使用它来发起请求和处理请求回调结果。代码如下:

@Resource
private RestTemplate restTemplate;

/**
 * 使用RestTemplate来处理http请求
 * @return
 * @throws IOException
 */
@GetMapping("/restTemplateTest")
public String restTemplateTest() {
    // 打印请求结果
    System.out.println(restTemplate.getForObject(SERVICE_URL + "/hello", String.class));
    return "请求成功";
}

在这里插入图片描述

使用WebClient处理请求

在这里插入图片描述
复制request-demo为request-demo2,修改pom.xml文件中的web场景启动器为spring-boot-starter-webflux,然后新建ConsumerController2类,并新增如下代码:

package ltd.newbee.cloud.web;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@RestController
public class ConsumerController2 {

    private final String SERVICE_URL = "http://localhost:8081";
    //private final String SERVICE_URL = "http://localhost:8082";

    private WebClient webClient = WebClient.builder()
            .baseUrl(SERVICE_URL)
            .build();

    /**
     * 使用WebClient处理http请求
     * @return
     */
    @GetMapping("/webClientTest")
    public String webClientTest() {
        Mono<String> mono = webClient
                .get() // GET 请求方式
                .uri("/hello")  // 请求地址
                .retrieve() // 获取响应结果
                .bodyToMono(String.class); //响应结果转换

        // 打印请求结果
        mono.subscribe(result -> {
            System.out.println(result);
        });
        return "请求成功";
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gary jie

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值