Spring Boot集成Stripe快速入门demo

news2024/11/16 1:25:32

1.什么是Stripe?

一体化全球支付平台,开启收入增长引擎,针对不同规模业务打造的支付解决方案,满足从初创公司到跨国企业的多维度需求,助力全球范围内线上线下付款。

  • 转化更多客户: 通过内置的优化功能、100 多种支付方式及一键结账来提高转化率。实现线上和线下付款一体化,提供无缝的客户体验。
  • 全球覆盖,本地体验: 引入多样化支付方式,采用当地货币呈现价格,以此快速拓展新市场,实现向 195+ 个国家/地区的跨境销售,有效降低管理多币种的成本。
  • 减少欺诈,增加收入: Stripe 的机器学习优化功能基于数十亿数据点进行深度训练,为您自动降低欺诈风险,同时提升交易授权率。
  • 降本增效,快速拓展: 通过提高开发人员的工作效率,节省时间和工程资源。凭借领先的可靠性避免宕机,并通过替代支付方式和路径降低成本。

2.代码工程

实验目标

1.实现一次支付功能
2.实现订阅支付功能

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>stripe</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.sparkjava</groupId>
            <artifactId>spark-core</artifactId>
            <version>2.9.4</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.stripe</groupId>
            <artifactId>stripe-java</artifactId>
            <version>25.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>
</project>

controller

package com.et.stripe.controller;

import com.et.stripe.common.Response;
import com.et.stripe.service.StripeService;

import com.stripe.model.Coupon;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class PaymentController {

    @Value("${stripe.keys.public}")
    private String API_PUBLIC_KEY;

    private StripeService stripeService;

    public PaymentController(StripeService stripeService) {
        this.stripeService = stripeService;
    }

    @GetMapping("/")
    public String homepage() {
        return "homepage";
    }

    @GetMapping("/subscription")
    public String subscriptionPage(Model model) {
        model.addAttribute("stripePublicKey", API_PUBLIC_KEY);
        return "subscription";
    }

    @GetMapping("/charge")
    public String chargePage(Model model) {
        model.addAttribute("stripePublicKey", API_PUBLIC_KEY);
        return "charge";
    }

    /*========== REST APIs for Handling Payments ===================*/

    @PostMapping("/create-subscription")
    public @ResponseBody
    Response createSubscription(String email, String token, String plan, String coupon) {
        //validate data
        if (token == null || plan.isEmpty()) {
            return new Response(false, "Stripe payment token is missing. Please, try again later.");
        }

        //create customer first
        String customerId = stripeService.createCustomer(email, token);

        if (customerId == null) {
            return new Response(false, "An error occurred while trying to create a customer.");
        }

        //create subscription
        String subscriptionId = stripeService.createSubscription(customerId, plan, coupon);
        if (subscriptionId == null) {
            return new Response(false, "An error occurred while trying to create a subscription.");
        }

        // Ideally you should store customerId and subscriptionId along with customer object here.
        // These values are required to update or cancel the subscription at later stage.

        return new Response(true, "Success! Your subscription id is " + subscriptionId);
    }

    @PostMapping("/cancel-subscription")
    public @ResponseBody
    Response cancelSubscription(String subscriptionId) {
        boolean status = stripeService.cancelSubscription(subscriptionId);
        if (!status) {
            return new Response(false, "Failed to cancel the subscription. Please, try later.");
        }
        return new Response(true, "Subscription cancelled successfully.");
    }

    @PostMapping("/coupon-validator")
    public @ResponseBody
    Response couponValidator(String code) {
        Coupon coupon = stripeService.retrieveCoupon(code);
        if (coupon != null && coupon.getValid()) {
            String details = (coupon.getPercentOff() == null ? "$" + (coupon.getAmountOff() / 100) : coupon.getPercentOff() + "%") +
                    " OFF " + coupon.getDuration();
            return new Response(true, details);
        } else {
            return new Response(false, "This coupon code is not available. This may be because it has expired or has " +
                    "already been applied to your account.");
        }
    }

    @PostMapping("/create-charge")
    public @ResponseBody
    Response createCharge(String email, String token) {
        //validate data
        if (token == null) {
            return new Response(false, "Stripe payment token is missing. Please, try again later.");
        }

        //create charge
        String chargeId = stripeService.createCharge(email, token, 999); //$9.99 USD
        if (chargeId == null) {
            return new Response(false, "An error occurred while trying to create a charge.");
        }

        // You may want to store charge id along with order information

        return new Response(true, "Success! Your charge id is " + chargeId);
    }
}

service

package com.et.stripe.service;

import com.stripe.Stripe;
import com.stripe.model.Charge;
import com.stripe.model.Coupon;
import com.stripe.model.Customer;
import com.stripe.model.Subscription;
import com.stripe.param.SubscriptionCancelParams;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class StripeService {

    @Value("${stripe.keys.secret}")
    private String API_SECRET_KEY;

    public StripeService() {
    }

    public String createCustomer(String email, String token) {
        String id = null;
        try {
            Stripe.apiKey = API_SECRET_KEY;
            Map<String, Object> customerParams = new HashMap<>();
            // add customer unique id here to track them in your web application
            customerParams.put("description", "Customer for " + email);
            customerParams.put("email", email);

            customerParams.put("source", token); // ^ obtained with Stripe.js
            //create a new customer
            Customer customer = Customer.create(customerParams);
            id = customer.getId();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return id;
    }

    public String createSubscription(String customerId, String plan, String coupon) {
        String id = null;
        try {
            Stripe.apiKey = API_SECRET_KEY;
            Map<String, Object> item = new HashMap<>();
            item.put("price", plan);

            Map<String, Object> items = new HashMap<>();
            items.put("0", item);

            Map<String, Object> params = new HashMap<>();
            params.put("customer", customerId);
            params.put("items", items);

            //add coupon if available
            if (!coupon.isEmpty()) {
                params.put("coupon", coupon);
            }

            Subscription sub = Subscription.create(params);
            id = sub.getId();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return id;
    }

    public boolean cancelSubscription(String subscriptionId) {
        boolean status;
        try {
            Stripe.apiKey = API_SECRET_KEY;
            Subscription sub = Subscription.retrieve(subscriptionId);
            sub.cancel((SubscriptionCancelParams) null);
            status = true;
        } catch (Exception ex) {
            ex.printStackTrace();
            status = false;
        }
        return status;
    }

    public Coupon retrieveCoupon(String code) {
        try {
            Stripe.apiKey = API_SECRET_KEY;
            return Coupon.retrieve(code);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public String createCharge(String email, String token, int amount) {
        String id = null;
        try {
            Stripe.apiKey = API_SECRET_KEY;
            Map<String, Object> chargeParams = new HashMap<>();
            chargeParams.put("amount", amount);
            chargeParams.put("currency", "usd");
            chargeParams.put("description", "Charge for " + email);
            chargeParams.put("source", token); // ^ obtained with Stripe.js

            //create a charge
            Charge charge = Charge.create(chargeParams);
            id = charge.getId();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return id;
    }

}

templates

homepage

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Homepage</title>
    <!--Bootstrap 4 CSS-->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

    <!--Bootstrap 4 JavaScript-->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body class="bg-light pt-5">

<!--hero section-->
<section class="py-5">
    <div class="container">
        <div class="row">
            <div class="col-lg-7 col-md-10 col-12 my-auto mx-auto text-center">
                <h1>
                    Stripe Payment Examples
                </h1>
                <p class="lead mb-4">
                    What would you like to do?
                </p>
                <a class="btn btn-primary" th:href="@{/subscription}">Create Recurring Subscription</a>
                <a class="btn btn-success" th:href="@{/charge}">Create One-Time Charge</a>
                <p class="mt-5 text-muted">
                    <small>An example project by <a target="_blank"
                                                    th:href="@{https://attacomsian.com}">Atta</a>.</small>
                </p>
            </div>
        </div>
    </div>
</section>

</body>
</html>

charge

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Charge</title>
    <!--Bootstrap 4 CSS-->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

    <!--Bootstrap 4 JavaScript-->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

    <!--Stripe JavaScript Library-->
    <script src="https://js.stripe.com/v3/"></script>
</head>
<body class="bg-light pt-5">

<!--hero section-->
<section class="py-5">
    <div class="container">
        <div class="row">
            <div class="col-lg-6 col-md-8 col-12 my-auto mx-auto">
                <h1>
                    Stripe One-Time Charge
                </h1>
                <p class="lead mb-4">
                    Please fill the form below to complete the order payment
                </p>
                <div class="card mb-4">
                    <div class="card-body">
                        <h5>Leather Bag</h5>
                        <p class="lead">USD 9.99</p>
                    </div>
                </div>
                <form action="#" id="payment-form" method="post">
                    <input id="api-key" th:value="${stripePublicKey}" type="hidden">
                    <div class="form-group">
                        <label class="font-weight-medium" for="card-element">
                            Enter credit or debit card below
                        </label>
                        <div class="w-100" id="card-element">
                            <!-- A Stripe Element will be inserted here. -->
                        </div>
                    </div>
                    <div class="form-group">
                        <input class="form-control" id="email" name="email"
                               placeholder="Email Address" required type="email">
                    </div>
                    <!-- Used to display Element errors. -->
                    <div class="text-danger w-100" id="card-errors" role="alert"></div>
                    <div class="form-group pt-2">
                        <button class="btn btn-primary btn-block" id="submitButton" type="submit">
                            Pay With Your Card
                        </button>
                        <div class="small text-muted mt-2">
                            Pay securely with Stripe. By clicking the button above, you agree
                            to our <a href="#" target="_blank">Terms of Service</a>,
                            <a href="#" target="_blank">Privacy</a> and
                            <a href="#" target="_blank">Refund</a> policies.

                        </div>
                    </div>


                </form>
                <p class="mt-5 text-muted">
                    <small>An example project by <a target="_blank" th:href="@{https://attacomsian.com}">Atta</a>.
                    </small>
                </p>
            </div>
        </div>
    </div>
</section>

<!--custom javascript for handling subscription-->
<script>
    $(function () {
        var API_KEY = $('#api-key').val();
        // Create a Stripe client.
        var stripe = Stripe(API_KEY);
        // Create an instance of Elements.
        var elements = stripe.elements();
        // Create an instance of the card Element.
        var card = elements.create('card');
        // Add an instance of the card Element into the `card-element` <div>.
        card.mount('#card-element');
        // Handle real-time validation errors from the card Element.
        card.addEventListener('change', function (event) {
            var displayError = document.getElementById('card-errors');
            if (event.error) {
                displayError.textContent = event.error.message;
            } else {
                displayError.textContent = '';
            }
        });
        // Handle form submission.
        var form = document.getElementById('payment-form');
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            // handle payment
            handlePayments();
        });

        //handle card submission
        function handlePayments() {
            stripe.createToken(card).then(function (result) {
                if (result.error) {
                    // Inform the user if there was an error.
                    var errorElement = document.getElementById('card-errors');
                    errorElement.textContent = result.error.message;
                } else {
                    // Send the token to your server.
                    var token = result.token.id;
                    var email = $('#email').val();
                    $.post(
                        "/create-charge",
                        {email: email, token: token},
                        function (data) {
                            alert(data.details);
                        }, 'json');
                }
            });
        }
    });
</script>

</body>
</html>

subscription

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Subscription</title>
    <!--Bootstrap 4 CSS-->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

    <!--Bootstrap 4 JavaScript-->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

    <!--Stripe JavaScript Library-->
    <script src="https://js.stripe.com/v3/"></script>
</head>
<body class="bg-light pt-5">

<!--hero section-->
<section class="py-5">
    <div class="container">
        <div class="row">
            <div class="col-lg-6 col-md-8 col-12 my-auto mx-auto">
                <h1>
                    Stripe Recurring Subscription
                </h1>
                <p class="lead mb-4">
                    Please fill the form below to complete the payment
                </p>
                <h5 class="mb-2">Choose your payment plan</h5>
                <p class="text-muted">
                    60% OFF when you upgrade to annual plan.
                </p>
                <div class="py-2">
                    <div class="custom-control custom-radio">
                        <input class="custom-control-input" id="monthly-plan" name="premium-plan" type="radio"
                               value="price_1PtRC5KYHXnPEBSj85nrvuKC"/>
                        <label class="custom-control-label" for="monthly-plan">
                            <strong>Monthly $9.99</strong><br/>
                            <small class="text-muted">
                                Pay $9.99 every month and get access to all premium features.
                            </small>
                        </label>
                    </div>
                    <div class="custom-control custom-radio mt-3">
                        <input checked="" class="custom-control-input" id="annually-plan" name="premium-plan"
                               type="radio" value="annual-subscription"/>
                        <label class="custom-control-label" for="annually-plan">
                            <strong>Yearly $49.99</strong>
                            <span class="badge badge-primary ml-1">60% OFF</span>
                            <br/>
                            <small class="text-muted">
                                Pay $49.99 every year and get access to all premium features.
                            </small>
                        </label>
                    </div>
                </div>
                <form action="#" id="payment-form" method="post">
                    <input id="api-key" th:value="${stripePublicKey}" type="hidden">
                    <div class="form-group">
                        <label class="font-weight-medium" for="card-element">
                            Enter credit or debit card below
                        </label>
                        <div class="w-100" id="card-element">
                            <!-- A Stripe Element will be inserted here. -->
                        </div>
                    </div>
                    <div class="form-group">
                        <input class="form-control" id="email" name="email"
                               placeholder="Email Address" required type="email">
                    </div>
                    <div class="form-group">
                        <input class="form-control" id="coupon" name="coupon"
                               placeholder="Coupon code (optional)" type="text">
                    </div>
                    <!-- Used to display Element errors. -->
                    <div class="text-danger w-100" id="card-errors" role="alert"></div>
                    <div class="form-group pt-2">
                        <button class="btn btn-primary btn-block" id="submitButton" type="submit">
                            Pay With Your Card
                        </button>
                        <div class="small text-muted mt-2">
                            Pay securely with Stripe. By clicking the button above, you agree
                            to our <a href="#" target="_blank">Terms of Service</a>,
                            <a href="#" target="_blank">Privacy</a> and
                            <a href="#" target="_blank">Refund</a> policies.

                        </div>
                    </div>


                </form>
                <p class="mt-5 text-muted">
                    <small>An example project by <a target="_blank" th:href="@{https://attacomsian.com}">Atta</a>.
                    </small>
                </p>
            </div>
        </div>
    </div>
</section>

<!--custom javascript for handling subscription-->
<script>
    $(function () {
        var API_KEY = $('#api-key').val();
        // Create a Stripe client.
        var stripe = Stripe(API_KEY);
        // Create an instance of Elements.
        var elements = stripe.elements();
        // Create an instance of the card Element.
        var card = elements.create('card');
        // Add an instance of the card Element into the `card-element` <div>.
        card.mount('#card-element');
        // Handle real-time validation errors from the card Element.
        card.addEventListener('change', function (event) {
            var displayError = document.getElementById('card-errors');
            if (event.error) {
                displayError.textContent = event.error.message;
            } else {
                displayError.textContent = '';
            }
        });
        // Handle form submission.
        var form = document.getElementById('payment-form');
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            //validate coupon if any
            var code = $('#coupon').val().trim();
            if (code.length > 0) {
                $.post(
                    "/coupon-validator",
                    {code: code},
                    function (data) {
                        if (data.status) {
                            handlePayments();
                        } else {
                            alert(data.details);
                        }
                    }, 'json');
            } else {
                handlePayments();
            }
        });

        //handle card submission
        function handlePayments() {
            stripe.createToken(card).then(function (result) {
                if (result.error) {
                    // Inform the user if there was an error.
                    var errorElement = document.getElementById('card-errors');
                    errorElement.textContent = result.error.message;
                } else {
                    // Send the token to your server.
                    var token = result.token.id;
                    var plan = $('input[name="premium-plan"]:checked').val();
                    var email = $('#email').val();
                    var coupon = $('#coupon').val();
                    $.post(
                        "/create-subscription",
                        {email: email, token: token, plan: plan, coupon: coupon},
                        function (data) {
                            alert(data.details);
                        }, 'json');
                }
            });
        }
    });
</script>

</body>
</html>

application.yaml

#Stripe keys - REPLACE WITH ACTUAL KEYS
stripe.keys.public=pk_test_xxxxx
stripe.keys.secret=sk_test_xxxxx
#Don't cache thymeleaf files - FOR TEST PURPOSE ONLY
spring.thymeleaf.cache=false

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • GitHub - Harries/springboot-demo: a simple springboot demo with some components for example: redis,solr,rockmq and so on.(stripe)

3.测试

启动Spring Boot应用

一次支付测试

http://127.0.0.1:8080/charge

charge

可以在这个地址 Test card numbers | Stripe Documentation,找到测试卡号, 输入测试卡号,显示支付成功

charge-success

订阅支付测试

http://127.0.0.1:8080/subscription

subscription

输入测试卡号,显示订阅成功(注意:是订阅产品上创建多个价格,而不是创建多个产品)

subscription-success

stripe控制台交易信息

transactions

4.引用

  • Test card numbers | Stripe Documentation
  • Stripe | Financial Infrastructure to Grow Your Revenue
  • Spring Boot集成Stripe快速入门demo | Harries Blog™

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2093134.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

QT QGraphicsView实现预览图片显示缩略图功能

QT QGraphicsView实现预览图片显示缩略图功能QT creator Qt5.15.2 头文件&#xff1a; #ifndef TGRAPHICSVIEW_H #define TGRAPHICSVIEW_H#include <QGraphicsView> #include <QMainWindow> #include <QObject> #include <QWidget>class TGraphicsVie…

vue页面自适应 动态 postcss postcss-pxtorem

vue页面自适应 动态 postcss postcss-pxtorem postcss-pxtorem实现页面自适应1、安装postcss-pxtorem2、根目录创建postcss.config.js&#xff0c;并配置以下内容3、创建rem.js&#xff0c;动态设置root px4、在main.js中引入rem.js5、在main.js中创建全局处理函数px2rem6、对…

【王树森】Vision Transformer (ViT) 用于图片分类(个人向笔记)

图片分类任务 给定一张图片&#xff0c;现在要求神经网络能够输出它对这个图片的分类结果。下图表示神经网络有40%的信心认定这个图片是狗 ResNet&#xff08;CNN&#xff09;曾经是是图像分类的最好模型在有足够大数据做预训练的情况下&#xff0c;ViT要强于ResNetViT 就是Tr…

S7-200编程软件STEP 7打开时界面乱码显示Translation Required

遇到的问题 如题&#xff0c;两个月没有打开过S7-200编程软件&#xff08;软件版本是V4.0 STEP 7 MicroWIN SP9&#xff0c;电脑系统是Windows 11&#xff09;&#xff0c;这一次打开就发现它的那个界面乱码了&#xff0c;原来时中文汉化的地方全都变成了Translation Required…

笔记整理—内核!启动!—uboot部分(1)

常规启动时&#xff0c;各镜像都在SD卡中的各种分区中&#xff0c;内核放在kernel分区&#xff0c;从SD卡到DDR的连接处&#xff08;内核不需要进行重定位&#xff0c;直接从链接处启动&#xff09;。uboot从sd卡分区读使用movi命令。 使用fastboot指令可以查看分区情况&#x…

通过Dot1q终结子接口实现VLAN间互访

如图1所示&#xff0c;SwitchA为支持配置子接口的三层交换机&#xff0c;SwitchB为二层交换机&#xff0c;SwitchA通过一个三层以太网接口与SwitchB互连。用户主机被划分到两个VLAN&#xff1a;VLAN2和VLAN3。由于业务需要&#xff0c;不同VLAN的用户要求互通。 图1 通过Dot1q…

AI革命:清华大学揭秘大模型工具学习的未来

&#x1f31f; 未来已来&#xff1a;大模型工具学习开启智能新时代 &#x1f31f; 清华大学THUNLP最新研究&#xff0c;探索AI工具使用的无限可能 文末有报告免费下载&#xff0c;需要的朋友自行下跳。 亲爱的读者朋友们&#xff0c;人工智能的浪潮已经不可阻挡地涌入我们的…

LabVIEW VI并行执行设置

要在多个程序中运行同一个VI&#xff08;Virtual Instrument&#xff09;&#xff0c;通常需要确保VI的重入性&#xff08;Reentrancy&#xff09;设置正确。在LabVIEW中&#xff0c;可以使用“重入性”&#xff08;Reentrancy&#xff09;选项来允许同一个VI同时在多个地方调用…

RAG噪声的设计及其对大模型问答的作用分析

有趣的大模型中RAG噪声的作用分析 大模型&#xff08;LLMs&#xff09;在多个任务上表现出色&#xff0c;但存在依赖过时知识、幻觉等问题。RAG作为一种提高LLM性能的方法&#xff0c;通过在推理过程中引入外部信息来缓解这些限制。 Figure 1 展示了一个来自 NoiserBench 的示…

Docker技术

一、Docker简介 1.什么是docker Docker是管理容器的引擎&#xff0c;为应用打包、部署平台&#xff0c;而非单纯的虚拟化技术。 它具有以下几个重要特点和优势&#xff1a; 1. 轻量级虚拟化 &#xff1a;Docker 容器相较于传统的虚拟机更加轻量和高效&#xff0c;能够快速启…

【高中数学/极值/判别式法】已知实数a和b,b在(0,1)区间,a-b=1,则1/(a-1)+1/(5-4b)的最小值是?

【问题】 已知实数a,b&#xff0c;b在(0,1)区间&#xff0c;a-b1,则1/(a-1)1/(5-4b)的最小值是&#xff1f; 【来源】 《解题卡壳怎么办 高中数学解题智慧点剖析》P34 余继光 苏德矿合著 浙江大学出版社出版 【破题点】 将a-1用b取代&#xff0c;发现结果是二次式相除&…

24-8-31-读书笔记(十六)-《契诃夫文集》(十一)([俄] 契诃夫 [译] 汝龙 )

文章目录 《契诃夫文集》&#xff08;十一&#xff09;&#xff08;[俄] 契诃夫 [译] 汝龙 &#xff09;目录阅读笔记记录总结 《契诃夫文集》&#xff08;十一&#xff09;&#xff08;[俄] 契诃夫 [译] 汝龙 &#xff09; 8月最后一天了&#xff0c;心里很多的感慨&#xff0…

Bluetooth: gatt server example 解读

在 core spec 中有 Example ATT Server contents,这里对此进行解读; Assigned_Numbers.pdf 需要提前准备,可以从 SIG 下载; Step-1 从这个服务看,server handle 是1, 但是第一个 characteristic clare handle是 4,所以不能预设handle 是按顺序连续的; Step-2 Servic…

强推第一本给程序员看的AI Agent教程终于来啦!全方位解析LLM-Agent

AI Agent火爆到什么程度&#xff1f; &#x1f340;OpenAI创始人奥特曼预测&#xff1a;未来各行各业&#xff0c;每一个人都可以拥有一个AI Agent。 &#x1f340;比尔盖茨在2023年曾预言&#xff1a;AI Agent将彻底改变人机交互方式&#xff0c;并颠覆整个软件行业。 &#x…

MATLAB生成COE文件

MATLAB代码 % 参数设置 N 4096; % 数据点数量 t linspace(0, 2*pi, N); % 时间向量 width 12; % 位宽% 正弦波&#xff0c;幅度在0到5之间 sine_wave 2.5 * sin(t) 2.5;% 三角波&#xff0c;幅度在0到5之间 tri_wave 5 * (1 - abs(mod(t/(2*pi)*4, 2) - 1));% 方波&…

记一次学习--webshell绕过

目录 第一题 第二题 第三题 第四题 第五题 第一题 <?php$action $_GET[action]; $parameters $_GET; if (isset($parameters[action])) {unset($parameters[action]); }$a call_user_func($action, ...$parameters); 上面题目&#xff0c;下面的call_user_func有一…

Spring 是什么

首先我们先看一个例子。以下是代码的结构。 public interface UserDAO {/*** 根据id删除用户*/void deleteById(); } public class UserDAOImplForMySQL implements UserDAO {Overridepublic void deleteById() {System.out.println("使用MySQL数据库删除信息....")…

day49 | 42. 接雨水 84. 柱状图中最大的矩形

代码随想录算法训练营第 49 天| 42. 接雨水 84. 柱状图中最大的矩形 Leetcode 42. 接雨水 题目链接&#xff1a;https://leetcode.cn/problems/trapping-rain-water/description/ 题目描述&#xff1a; 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图&#xff0c;计算按…

【第三期实战营闯关作业##LMDeploy 量化部署进阶实践】

《LMDeploy 量化部署进阶实践》这节课内容有些多&#xff0c;因此分了两部分提交了。以下是记录复现过程及截图; 这是执行了下面的命令&#xff0c;占用显存的情况。&#xff08;如截图顶部&#xff09; lmdeploy chat /root/models/internlm2_5-7b-chat --cache-max-entry-co…

视觉检索(以图搜图)技术分享

视觉检索&#xff08;Visual Retrieval&#xff09;是一个涉及计算机视觉和图像处理的技术领域&#xff0c;主要目标是从大量的视觉数据中找到与查询图像或视频相关的内容。视觉检索技术在多个领域都有广泛应用&#xff0c;如医疗图像分析、安全监控、机器人视觉、电子商务等。…