首页 > 编程语言 >RocketMQ 入门实战(4)--Java 操作 RocketMQ

RocketMQ 入门实战(4)--Java 操作 RocketMQ

时间:2023-09-17 11:13:47浏览次数:42  
标签:ClientServiceProvider Java -- subscriptionExpressions TOPIC build provider messa

本文主要介绍使用 Java 来操作 RocketMQ,文中所使用到的软件版本:Java 1.8.0_341、RocketMQ 5.1.3、rocketmq-client-java 5.0.5。

1、引入依赖

<dependency>
    <groupId>org.apache.rocketmq</groupId>
    <artifactId>rocketmq-client-java</artifactId>
    <version>5.0.5</version>
</dependency>

2、Java 操作 RocketMQ

2.1、创建主题

bin/mqadmin updateTopic -n 10.49.196.33:9876 -t NORMAL_TOPIC -c DefaultCluster -a +message.type=NORMAL #普通消息
bin/mqadmin updateTopic -n 10.49.196.33:9876 -t DELAY_TOPIC -c DefaultCluster -a +message.type=DELAY #定时/延时消息
bin/mqadmin updateTopic -n 10.49.196.33:9876 -t FIFO_TOPIC -c DefaultCluster -a +message.type=FIFO #顺序消息
bin/mqadmin updateTopic -n 10.49.196.33:9876 -t TRANSACTION_TOPIC -c DefaultCluster -a +message.type=TRANSACTION #事务消息

2.2、生产者

2.1.1、普通消息

A、同步发送

@Test
public void normal() throws ClientException, IOException {
    ClientServiceProvider provider = ClientServiceProvider.loadService();
    //SessionCredentialsProvider sessionCredentialsProvider = new StaticSessionCredentialsProvider("RocketMQ", "12345678");
    ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
            .setEndpoints(endpoints)
            //.setCredentialProvider(sessionCredentialsProvider)
            .build();
    String topic = "NORMAL_TOPIC";
    Producer producer = provider.newProducerBuilder()
            .setTopics(topic)
            .setClientConfiguration(clientConfiguration)
            .build();
    Message message = provider.newMessageBuilder()
            .setTopic(topic)
            .setKeys("messageKey", "messageKey2")
            .setTag("messageTag")
            .setBody("normalMessage".getBytes())
            .build();
    SendReceipt sendReceipt = producer.send(message);
    log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());
    producer.close();
}

B、异步发送

@Test
public void normalAsync() throws ClientException, InterruptedException {
    ClientServiceProvider provider = ClientServiceProvider.loadService();
    ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder().setEndpoints(endpoints).build();
    String topic = "NORMAL_TOPIC";
    Producer producer = provider.newProducerBuilder()
            .setTopics(topic)
            .setClientConfiguration(clientConfiguration)
            .build();
    Message message = provider.newMessageBuilder()
            .setTopic(topic)
            .setKeys("messageKey", "messageKey2")
            .setTag("messageTag")
            .setBody("normalMessage".getBytes())
            .build();
    CompletableFuture<SendReceipt> sendReceiptCompletableFuture = producer.sendAsync(message);
    sendReceiptCompletableFuture.whenComplete(new BiConsumer<SendReceipt, Throwable>() {
        @Override
        public void accept(SendReceipt sendReceipt, Throwable throwable) {
            log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());
        }
    });
    Thread.sleep(Long.MAX_VALUE);
}

2.1.2、定时/延时消息

@Test
public void delay() throws ClientException, IOException {
    ClientServiceProvider provider = ClientServiceProvider.loadService();
    ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder().setEndpoints(endpoints).build();
    String topic = "DELAY_TOPIC";
    Producer producer = provider.newProducerBuilder()
            .setTopics(topic)
            .setClientConfiguration(clientConfiguration)
            .build();
    Long deliverTimeStamp = System.currentTimeMillis() + 1 * 60 * 1000;
    Message message = provider.newMessageBuilder()
            .setTopic(topic)
            .setKeys("messageKey", "messageKey2")
            .setTag("messageTag")
            .setBody(("delayMessage-" + LocalDateTime.now()).getBytes())
            .setDeliveryTimestamp(deliverTimeStamp)
            .build();
    SendReceipt sendReceipt = producer.send(message);
    log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());
    producer.close();
}

2.1.3、顺序消息

@Test
public void fifo() throws ClientException, IOException {
    ClientServiceProvider provider = ClientServiceProvider.loadService();
    ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder().setEndpoints(endpoints).build();
    String topic = "FIFO_TOPIC";
    Producer producer = provider.newProducerBuilder()
            .setTopics(topic)
            .setClientConfiguration(clientConfiguration)
            .build();
    Message message = provider.newMessageBuilder()
            .setTopic(topic)
            .setKeys("messageKey", "messageKey2")
            .setTag("messageTag")
            .setBody(("fifoMessage").getBytes())
            .setMessageGroup("fifoGroup")
            .build();
    SendReceipt sendReceipt = producer.send(message);
    log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());

    producer.close();
}

2.1.4、事务消息

@Test
public void transaction() throws ClientException, IOException {
    ClientServiceProvider provider = ClientServiceProvider.loadService();
    ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder().setEndpoints(endpoints).build();
    String topic = "TRANSACTION_TOPIC";
    Producer producer = provider.newProducerBuilder()
            .setTopics(topic)
            .setClientConfiguration(clientConfiguration)
            .setTransactionChecker(new TransactionChecker() {
                @Override
                public TransactionResolution check(MessageView messageView) {
                    TransactionResolution result = TransactionResolution.COMMIT;
                    //TODO:检查业务是否正常处理,如果失败则 result = TransactionResolution.ROLLBACK
                    return result;
                }
            })
            .build();
    Message message = provider.newMessageBuilder()
            .setTopic(topic)
            .setKeys("messageKey", "messageKey2")
            .setTag("messageTag")
            .setBody(("transactionMessage").getBytes())
            .build();
    Transaction transaction = producer.beginTransaction();
    try {
        SendReceipt sendReceipt = producer.send(message, transaction);
        log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());

        //TODO:业务处理

        transaction.commit();
    } catch (Exception e) {
        transaction.rollback();
    }
    producer.close();
}

2.3、消费者

2.3.1、PushConsumer

@Test
public void pushConsumer() throws ClientException, InterruptedException {
    ClientServiceProvider provider = ClientServiceProvider.loadService();
    ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
            .setEndpoints(endpoints)
            .build();
    FilterExpression filterExpression = new FilterExpression("*", FilterExpressionType.TAG);
    Map<String, FilterExpression> subscriptionExpressions = new HashMap<>();
    subscriptionExpressions.put("NORMAL_TOPIC", filterExpression);
    subscriptionExpressions.put("DELAY_TOPIC", filterExpression);
    subscriptionExpressions.put("FIFO_TOPIC", filterExpression);
    subscriptionExpressions.put("TRANSACTION_TOPIC", filterExpression);
    PushConsumer pushConsumer = provider.newPushConsumerBuilder()
            .setClientConfiguration(clientConfiguration)
            .setConsumerGroup(group)
            .setSubscriptionExpressions(subscriptionExpressions)
            .setMessageListener(messageView -> {
                log.info("接受到消息:messageId={},body={}", messageView.getMessageId(), StandardCharsets.UTF_8.decode(messageView.getBody()));
                return ConsumeResult.SUCCESS;
            }).build();
    log.info("开始接受消息...");
    Thread.sleep(Long.MAX_VALUE);
}

2.3.2、SimpleConsumer

A、同步订阅

@Test
public void simpleConsumer() throws ClientException {
    ClientServiceProvider provider = ClientServiceProvider.loadService();
    ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
            .setEndpoints(endpoints)
            .build();
    FilterExpression filterExpression = new FilterExpression("*", FilterExpressionType.TAG);
    Map<String, FilterExpression> subscriptionExpressions = new HashMap<>();
    subscriptionExpressions.put("NORMAL_TOPIC", filterExpression);
    subscriptionExpressions.put("DELAY_TOPIC", filterExpression);
    subscriptionExpressions.put("FIFO_TOPIC", filterExpression);
    subscriptionExpressions.put("TRANSACTION_TOPIC", filterExpression);
    SimpleConsumer simpleConsumer = provider.newSimpleConsumerBuilder()
            .setClientConfiguration(clientConfiguration)
            .setConsumerGroup(group)
            .setSubscriptionExpressions(subscriptionExpressions)
            .setAwaitDuration(Duration.ofSeconds(30))
            .build();
    log.info("开始接受消息...");
    while (true) {
        List<MessageView> messageViews = simpleConsumer.receive(10, Duration.ofSeconds(30));
        for (MessageView messageView : messageViews) {
            log.info("接受到消息:messageId={},body={}", messageView.getMessageId(), StandardCharsets.UTF_8.decode(messageView.getBody()));
            simpleConsumer.ack(messageView);
        }
    }
}

B、异步订阅

@Test
public void simpleConsumerAsync() throws ClientException {
    ClientServiceProvider provider = ClientServiceProvider.loadService();
    ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
            .setEndpoints(endpoints)
            .build();
    FilterExpression filterExpression = new FilterExpression("*", FilterExpressionType.TAG);
    Map<String, FilterExpression> subscriptionExpressions = new HashMap<>();
    subscriptionExpressions.put("NORMAL_TOPIC", filterExpression);
    subscriptionExpressions.put("DELAY_TOPIC", filterExpression);
    subscriptionExpressions.put("FIFO_TOPIC", filterExpression);
    subscriptionExpressions.put("TRANSACTION_TOPIC", filterExpression);
    SimpleConsumer simpleConsumer = provider.newSimpleConsumerBuilder()
            .setClientConfiguration(clientConfiguration)
            .setConsumerGroup(group)
            .setSubscriptionExpressions(subscriptionExpressions)
            .setAwaitDuration(Duration.ofSeconds(30))
            .build();
    log.info("开始接受消息...");
    while (true) {
        CompletableFuture<List<MessageView>> future = simpleConsumer.receiveAsync(10, Duration.ofSeconds(30));
        future.whenCompleteAsync((messageViews, throwable) -> {
            if (throwable != null) {
                log.error("Failed to receive message", throwable);
                return;
            }
            for (MessageView messageView : messageViews) {
                log.info("接受到消息:messageId={},body={}", messageView.getMessageId(), StandardCharsets.UTF_8.decode(messageView.getBody()));
                CompletableFuture<Void> completableFuture = simpleConsumer.ackAsync(messageView);
                completableFuture.whenCompleteAsync(new BiConsumer<Void, Throwable>() {
                    @Override
                    public void accept(Void unused, Throwable throwable) {
                        if (null != throwable) {
                            log.error("Message is failed to be acknowledged, messageId={}", messageView.getMessageId(), throwable);
                            return;
                        }
                        log.info("Message is acknowledged successfully, messageId={}", messageView.getMessageId());
                    }
                });
            }
        });
    }
}

异步订阅会报错:DEADLINE_EXCEEDED: deadline exceeded after 32.999993800s;可能是 RocketMQ 的 bug。

2.4、完整代码

2.4.1、生产者

package com.abc.demo.rocketmq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.*;
import org.apache.rocketmq.client.apis.message.Message;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.apache.rocketmq.client.apis.producer.*;
import org.junit.Test;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;

@Slf4j
public class ProducerCase {
    private static final String endpoints = "10.49.196.33:8081";

    @Test
    public void normal() throws ClientException, IOException {
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        //SessionCredentialsProvider sessionCredentialsProvider = new StaticSessionCredentialsProvider("RocketMQ", "12345678");
        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
                .setEndpoints(endpoints)
                //.setCredentialProvider(sessionCredentialsProvider)
                .build();
        String topic = "NORMAL_TOPIC";
        Producer producer = provider.newProducerBuilder()
                .setTopics(topic)
                .setClientConfiguration(clientConfiguration)
                .build();
        Message message = provider.newMessageBuilder()
                .setTopic(topic)
                .setKeys("messageKey", "messageKey2")
                .setTag("messageTag")
                .setBody("normalMessage".getBytes())
                .build();
        SendReceipt sendReceipt = producer.send(message);
        log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());
        producer.close();
    }

    @Test
    public void normalAsync() throws ClientException, InterruptedException {
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder().setEndpoints(endpoints).build();
        String topic = "NORMAL_TOPIC";
        Producer producer = provider.newProducerBuilder()
                .setTopics(topic)
                .setClientConfiguration(clientConfiguration)
                .build();
        Message message = provider.newMessageBuilder()
                .setTopic(topic)
                .setKeys("messageKey", "messageKey2")
                .setTag("messageTag")
                .setBody("normalMessage".getBytes())
                .build();
        CompletableFuture<SendReceipt> sendReceiptCompletableFuture = producer.sendAsync(message);
        sendReceiptCompletableFuture.whenComplete(new BiConsumer<SendReceipt, Throwable>() {
            @Override
            public void accept(SendReceipt sendReceipt, Throwable throwable) {
                log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());
            }
        });
        Thread.sleep(Long.MAX_VALUE);
    }

    @Test
    public void delay() throws ClientException, IOException {
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder().setEndpoints(endpoints).build();
        String topic = "DELAY_TOPIC";
        Producer producer = provider.newProducerBuilder()
                .setTopics(topic)
                .setClientConfiguration(clientConfiguration)
                .build();
        Long deliverTimeStamp = System.currentTimeMillis() + 1 * 60 * 1000;
        Message message = provider.newMessageBuilder()
                .setTopic(topic)
                .setKeys("messageKey", "messageKey2")
                .setTag("messageTag")
                .setBody(("delayMessage-" + LocalDateTime.now()).getBytes())
                .setDeliveryTimestamp(deliverTimeStamp)
                .build();
        SendReceipt sendReceipt = producer.send(message);
        log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());
        producer.close();
    }

    @Test
    public void fifo() throws ClientException, IOException {
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder().setEndpoints(endpoints).build();
        String topic = "FIFO_TOPIC";
        Producer producer = provider.newProducerBuilder()
                .setTopics(topic)
                .setClientConfiguration(clientConfiguration)
                .build();
        Message message = provider.newMessageBuilder()
                .setTopic(topic)
                .setKeys("messageKey", "messageKey2")
                .setTag("messageTag")
                .setBody(("fifoMessage").getBytes())
                .setMessageGroup("fifoGroup")
                .build();
        SendReceipt sendReceipt = producer.send(message);
        log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());

        producer.close();
    }

    @Test
    public void transaction() throws ClientException, IOException {
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder().setEndpoints(endpoints).build();
        String topic = "TRANSACTION_TOPIC";
        Producer producer = provider.newProducerBuilder()
                .setTopics(topic)
                .setClientConfiguration(clientConfiguration)
                .setTransactionChecker(new TransactionChecker() {
                    @Override
                    public TransactionResolution check(MessageView messageView) {
                        TransactionResolution result = TransactionResolution.COMMIT;
                        //TODO:检查业务是否正常处理,如果失败则 result = TransactionResolution.ROLLBACK
                        return result;
                    }
                })
                .build();
        Message message = provider.newMessageBuilder()
                .setTopic(topic)
                .setKeys("messageKey", "messageKey2")
                .setTag("messageTag")
                .setBody(("transactionMessage").getBytes())
                .build();
        Transaction transaction = producer.beginTransaction();
        try {
            SendReceipt sendReceipt = producer.send(message, transaction);
            log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());

            //TODO:业务处理

            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
        }
        producer.close();
    }
}
ProducerCase

2.4.2、消费者

package com.abc.demo.rocketmq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.ClientConfiguration;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.consumer.*;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;

@Slf4j
public class ConsumerCase {
    private static final String endpoints = "10.49.196.33:8081";

    private static final String group = "myGroup";

    @Test
    public void pushConsumer() throws ClientException, InterruptedException {
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
                .setEndpoints(endpoints)
                .build();
        FilterExpression filterExpression = new FilterExpression("*", FilterExpressionType.TAG);
        Map<String, FilterExpression> subscriptionExpressions = new HashMap<>();
        subscriptionExpressions.put("NORMAL_TOPIC", filterExpression);
        subscriptionExpressions.put("DELAY_TOPIC", filterExpression);
        subscriptionExpressions.put("FIFO_TOPIC", filterExpression);
        subscriptionExpressions.put("TRANSACTION_TOPIC", filterExpression);
        PushConsumer pushConsumer = provider.newPushConsumerBuilder()
                .setClientConfiguration(clientConfiguration)
                .setConsumerGroup(group)
                .setSubscriptionExpressions(subscriptionExpressions)
                .setMessageListener(messageView -> {
                    log.info("接受到消息:messageId={},body={}", messageView.getMessageId(), StandardCharsets.UTF_8.decode(messageView.getBody()));
                    return ConsumeResult.SUCCESS;
                }).build();
        log.info("开始接受消息...");
        Thread.sleep(Long.MAX_VALUE);
    }

    @Test
    public void simpleConsumer() throws ClientException {
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
                .setEndpoints(endpoints)
                .build();
        FilterExpression filterExpression = new FilterExpression("*", FilterExpressionType.TAG);
        Map<String, FilterExpression> subscriptionExpressions = new HashMap<>();
        subscriptionExpressions.put("NORMAL_TOPIC", filterExpression);
        subscriptionExpressions.put("DELAY_TOPIC", filterExpression);
        subscriptionExpressions.put("FIFO_TOPIC", filterExpression);
        subscriptionExpressions.put("TRANSACTION_TOPIC", filterExpression);
        SimpleConsumer simpleConsumer = provider.newSimpleConsumerBuilder()
                .setClientConfiguration(clientConfiguration)
                .setConsumerGroup(group)
                .setSubscriptionExpressions(subscriptionExpressions)
                .setAwaitDuration(Duration.ofSeconds(30))
                .build();
        log.info("开始接受消息...");
        while (true) {
            List<MessageView> messageViews = simpleConsumer.receive(10, Duration.ofSeconds(30));
            for (MessageView messageView : messageViews) {
                log.info("接受到消息:messageId={},body={}", messageView.getMessageId(), StandardCharsets.UTF_8.decode(messageView.getBody()));
                simpleConsumer.ack(messageView);
            }
        }
    }

    /**
     * 该写法会报错:DEADLINE_EXCEEDED: deadline exceeded after 32.999993800s,可能是 RocketMQ 的 bug
     */
    @Test
    public void simpleConsumerAsync() throws ClientException {
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
                .setEndpoints(endpoints)
                .build();
        FilterExpression filterExpression = new FilterExpression("*", FilterExpressionType.TAG);
        Map<String, FilterExpression> subscriptionExpressions = new HashMap<>();
        subscriptionExpressions.put("NORMAL_TOPIC", filterExpression);
        subscriptionExpressions.put("DELAY_TOPIC", filterExpression);
        subscriptionExpressions.put("FIFO_TOPIC", filterExpression);
        subscriptionExpressions.put("TRANSACTION_TOPIC", filterExpression);
        SimpleConsumer simpleConsumer = provider.newSimpleConsumerBuilder()
                .setClientConfiguration(clientConfiguration)
                .setConsumerGroup(group)
                .setSubscriptionExpressions(subscriptionExpressions)
                .setAwaitDuration(Duration.ofSeconds(30))
                .build();
        log.info("开始接受消息...");
        while (true) {
            CompletableFuture<List<MessageView>> future = simpleConsumer.receiveAsync(10, Duration.ofSeconds(30));
            future.whenCompleteAsync((messageViews, throwable) -> {
                if (throwable != null) {
                    log.error("Failed to receive message", throwable);
                    return;
                }
                for (MessageView messageView : messageViews) {
                    log.info("接受到消息:messageId={},body={}", messageView.getMessageId(), StandardCharsets.UTF_8.decode(messageView.getBody()));
                    CompletableFuture<Void> completableFuture = simpleConsumer.ackAsync(messageView);
                    completableFuture.whenCompleteAsync(new BiConsumer<Void, Throwable>() {
                        @Override
                        public void accept(Void unused, Throwable throwable) {
                            if (null != throwable) {
                                log.error("Message is failed to be acknowledged, messageId={}", messageView.getMessageId(), throwable);
                                return;
                            }
                            log.info("Message is acknowledged successfully, messageId={}", messageView.getMessageId());
                        }
                    });
                }
            });
        }
    }
}
ConsumerCase

 

标签:ClientServiceProvider,Java,--,subscriptionExpressions,TOPIC,build,provider,messa
From: https://www.cnblogs.com/wuyongyin/p/17624789.html

相关文章

  • FastAPI学习-17.其它响应html,文件,视频或其它
    前言通过我们返回JSON类型的接口会比较多,除了返回JSON格式,还可以响应其它格式的内容JSONResponseContent-Type 会被设置成 application/jsonHTMLResponseContent-Type 会被设置成 text/htmlPlainTextResponse Content-Type 会被设置成text/plainORJSONResp......
  • FastAPI学习-18.Response 返回 XML 格式
    前言假设你想要返回一个 XML响应。你可以把你的XML内容放到一个字符串中,放到一个 Response 中,然后返回。Response自定义返回可以把XML内容放到一个字符串中,放到一个 Response 中,设置media_type="application/xml"fromfastapiimportFastAPI,Responseapp=Fa......
  • 9.17 小试牛刀
    实操设计小米官网网站设计顶层黑色导航(9.17)遇到的问题1.如何链接css?<linkrel="stylesheet"type="text/css"href="style.css"/>2.如何去除无序列表前面的小点?list-style:none;3.如何弄走链接的下划线?text-decoration:none;小米logo如何与其他文字并排?这个......
  • 逻辑结构设计
              ......
  • FastAPI学习-19.response 参数-修改状态码
    前言假设你想默认返回一个HTTP状态码为“OK”200。但如果数据不存在,你想创建它,并返回一个HTTP状态码为“CREATED”201。但你仍然希望能够使用response_model过滤和转换你返回的数据。对于这些情况,你可以使用一个response`参数。使用 response 参数status_code设置默认状......
  • FastAPI学习-21.response 参数-设置响应Cookies
    前言可以在 路径函数 中定义一个类型为 Response的参数,这样你就可以在这个临时响应对象中设置cookie了。response参数设置cookiesfromfastapiimportFastAPI,Responseapp=FastAPI()@app.post("/cookie-and-object/")defcreate_cookie(response:Response):......
  • 第九章学习笔记
    Unix/Linux系统编程学习笔记第九章知识点归纳以及最有收获的内容I/O库函数知识点总结1.文件操作open()函数:用于打开文件,可以指定文件名、模式(读取、写入、追加等)以及编码。文件模式(mode):包括读取模式('r')、写入模式('w')、追加模式('a')、二进制模式('b')等。close()函数:用于关......
  • FastAPI学习-20.response 参数-设置响应头部
    前言你可以在你的_路径操作函数_中声明一个Response类型的参数。设置响应头部你可以在这个_临时_响应对象中设置头部fromfastapiimportFastAPI,Responseapp=FastAPI()@app.get("/headers-and-object/")defget_headers(response:Response):response.headers......
  • 物理设计阶段与实施和维护
        ......
  • 2023 JavaScript想进 BAT 的必须要面对的面试题
    2023JavaScript面试题以及答案在本文中,您将学习面试中最常见的JavaScript面试问题和答案。在继续学习JavaScript面试问题和答案之前,我们首先学习完整的JavaScript教程。JavaScript(JS)是使用最广泛的轻量级脚本和编译编程语言,具有一流的功能,由BrendenEich于1995年开发。众所周......