惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V2EX - 技术
V2EX - 技术
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
宝玉的分享
宝玉的分享
F
Fortinet All Blogs
T
Tailwind CSS Blog
IT之家
IT之家
B
Blog
D
DataBreaches.Net
博客园 - 【当耐特】
G
Google Developers Blog
WordPress大学
WordPress大学
S
Securelist
A
Arctic Wolf
Project Zero
Project Zero
T
Tenable Blog
P
Privacy International News Feed
The GitHub Blog
The GitHub Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
S
Schneier on Security
L
LINUX DO - 热门话题
T
Threat Research - Cisco Blogs
P
Privacy & Cybersecurity Law Blog
M
MIT News - Artificial intelligence
Scott Helme
Scott Helme
Google DeepMind News
Google DeepMind News
Simon Willison's Weblog
Simon Willison's Weblog
C
CERT Recently Published Vulnerability Notes
雷峰网
雷峰网
The Register - Security
The Register - Security
T
Threatpost
Recorded Future
Recorded Future
C
Cyber Attacks, Cyber Crime and Cyber Security
AWS News Blog
AWS News Blog
D
Docker
Cyberwarzone
Cyberwarzone
PCI Perspectives
PCI Perspectives
L
LangChain Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
腾讯CDC
T
The Exploit Database - CXSecurity.com
V
V2EX
S
Secure Thoughts
Hacker News - Newest:
Hacker News - Newest: "LLM"
AI
AI
阮一峰的网络日志
阮一峰的网络日志
Schneier on Security
Schneier on Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
B
Blog RSS Feed
J
Java Code Geeks
酷 壳 – CoolShell
酷 壳 – CoolShell

博客园 - ®Geovin Du Dream Park™

go: Functional Options Pattern go:Timing Functions Pattern python: Timing Functions Pattern go: Steady-State Pattern python: Steady-State Pattern go: Handshaking Pattern python: Handshaking Pattern go: Fail-Fast Pattern go: Deadline Pattern python: Deadline Pattern go: Circuit-Breaker Pattern python: Circuit-Breaker Pattern go: Bulkheads Pattern python: Bulkheads Pattern go: Push & Pull Pattern python: Push & Pull Pattern python: Publish/Subscribe Pattern II go: Publish/Subscribe Pattern python: Publish/Subscribe Pattern go: Futures & Promises Pattern python: Futures & Promises Pattern go: Worker Pool Pattern go:Pipeline Pattern python: Worker Pool Pattern python: Pipeline Pattern go: Fan-Out Pattern python: Fan-Out Pattern go: Fan-In Pattern python: Fan-In Pattern Fan-In go: Producer Consumer  Pattern python: Producer Consumer Pattern go: Parallelism Pattern python: Parallelism Pattern go: Reactor Pattern python: Reactor Pattern go: Generators Pattern python: speech to text offline python: Generators Pattern go: Coroutines Pattern python:Coroutines Pattern go: Broadcast Pattern python: Broadcast Pattern python: Bounded Parallelism Pattern go: Bounded Parallelism Pattern python: N-Barrier Pattern go: N-Barrier Pattern python: Semaphore Pattern go: Semaphore Pattern python: Read-Write Lock Pattern go: Read-Write Lock Pattern python: Monitor Pattern go: Monitor Pattern python: Mutex Pattern go: Lock/Mutex Pattern Python: Condition Variable Pattern go:Condition Variable Pattern python: Registry Pattern python: Interpreter Pattern go: Interpreter Pattern go: Registry Pattern go: Memento Pattern go: Command Pattern go: State Pattern go:Template Method Pattern go: Strategy Pattern go: Visitor Pattern go: Observer Pattern go: Mediator Pattern go: Iterator Pattern go: Chain of Responsibility Pattern go: Proxy Pattern go:Decorator Pattern go: Facade Pattern go: Flyweight Pattern go: Composite Pattern go: Singleton Pattern go: Prototype Pattern go: Bridge Pattern go: Adapter Pattern go: Builder Pattern 密码进行加盐哈希 using CSharp,Python,Go,Java go: Abstract Factory Pattern go: Model,Interface,DAL ,Factory,BLL using mysql go: Simple Factory Pattern go: Factory Method Pattern go: goLang 在Windows环境搭建Go语言开发环境 CSharp: Parallel Extensions cpp: class python: 蝴蝶跟随鼠标 javascript: 中国历史人物热力分布图using echart javascript: 中国历史人物热力图 python: 初养龙虾微信纯文字自动回复using workBuddy python: object 入门 python: Factory Method Pattern python: Simple Factory Pattern python: Abstract Factory Pattern 区域化 代码 python: Null Object Pattern python: Builder Pattern python: Adapter Pattern
python: Fail-Fast Pattern I
®Geovin Du Dream Park™ · 2026-06-30 · via 博客园 - ®Geovin Du Dream Park™

项目结构:

image

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Fail-Fast Pattern 快速失败模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/6/30 7:03 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : fail_fast.py

class ResourceCheckFailedError(Exception):
    """
    快速失败:资源不可用"
    """
    pass



# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Fail-Fast Pattern 快速失败模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/6/30 7:04 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : inventory_repo.py
class InventoryRepository:
    """

    """
    def __init__(self):
        self.inventory = {
            "DIA001": 5,
            "DIA002": 0,
            "GOLD001": 20
        }

    def get_stock(self, product_id: str)->int|None:
        """

        :param product_id:
        :return:
        """
        return self.inventory.get(product_id, -1)

    def deduct_stock(self, product_id: str, quantity: int)->int|None:
        """

        :param product_id:
        :param quantity:
        :return:
        """
        self.inventory[product_id] -= quantity


# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Fail-Fast Pattern 快速失败模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/6/30 7:05 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : external_services_repo.py



class ExternalServices:
    """

    """
    def __init__(self):
        self.inventory_service = True
        self.payment_gateway = True
        self.quality_inspection = True
        self.invoice_service = True



# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Fail-Fast Pattern 快速失败模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/6/30 7:05 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : validation_service.py
from FailFastPattern.exceptions.fail_fast import ResourceCheckFailedError
from FailFastPattern.repository.external_services_repo import ExternalServices
from FailFastPattern.repository.inventory_repo import InventoryRepository

class ValidationService:
    """

    """

    def __init__(
        self,
        inventory_repo: InventoryRepository,
        ext_services: ExternalServices
    ):
        self.inventory_repo = inventory_repo
        self.ext_services = ext_services

    def fail_fast_check(self, customer_id: str, product_id: str, quantity: int):
        """
        Fail-Fast 核心:全部资源一次性检查,不满足立即失败
        :param customer_id:
        :param product_id:
        :param quantity:
        :return:
        """

        # 1. 顾客检查
        if not customer_id or len(customer_id) < 3:
            raise ResourceCheckFailedError("顾客信息无效")

        # 2. 商品存在检查
        stock = self.inventory_repo.get_stock(product_id)
        if stock < 0:
            raise ResourceCheckFailedError(f"商品 {product_id} 不存在")

        # 3. 库存足够检查
        if stock < quantity:
            raise ResourceCheckFailedError(f"商品 {product_id} 库存不足")

        # 4. 外部服务检查
        if not self.ext_services.inventory_service:
            raise ResourceCheckFailedError("库存服务不可用")
        if not self.ext_services.payment_gateway:
            raise ResourceCheckFailedError("支付网关不可用")
        if not self.ext_services.quality_inspection:
            raise ResourceCheckFailedError("质检系统不可用")
        if not self.ext_services.invoice_service:
            raise ResourceCheckFailedError("发票系统不可用")



# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Fail-Fast Pattern 快速失败模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/6/30 7:06 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : order_service.py
from FailFastPattern.exceptions.fail_fast import ResourceCheckFailedError
from FailFastPattern.repository.external_services_repo import ExternalServices
from FailFastPattern.repository.inventory_repo import InventoryRepository
from FailFastPattern.service.validation_service import ValidationService
from ParallelismPattern.models.entities import Order


class OrderService:
    """

    """
    def __init__(
        self,
        validation_service: ValidationService,
        inventory_repo: InventoryRepository,
        ext_services: ExternalServices
    ):
        self.validation = validation_service
        self.inventory_repo = inventory_repo
        self.ext_services = ext_services

    def create_order(self, customer_id: str, product_id: str, quantity: int)->dict:
        """

        :param customer_id:
        :param product_id:
        :param quantity:
        :return:
        """
        try:
            # ========== 第一步:快速失败检查 ==========
            self.validation.fail_fast_check(customer_id, product_id, quantity)

            # ========== 检查通过:执行业务 ==========
            self.inventory_repo.deduct_stock(product_id, quantity)

            return {
                "order_id": "ORD-JWL-9999",
                "product_id": product_id,
                "quantity": quantity,
                "remaining_stock": self.inventory_repo.get_stock(product_id),
                "status": "success"
            }

        except ResourceCheckFailedError as e:
            raise e



# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Fail-Fast Pattern 快速失败模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/6/30 7:06 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : order_controller.py
from FailFastPattern.service.order_service import OrderService

class OrderController:
    """

    """
    def __init__(self, order_service: OrderService):
        self.order_service = order_service

    def create_jewelry_order(self, customer_id: str, product_id: str, quantity: int)->dict:
        """

        :param customer_id:
        :param product_id:
        :param quantity:
        :return:
        """
        try:
            result = self.order_service.create_order(customer_id, product_id, quantity)
            return {"success": True, "data": result}
        except Exception as e:
            return {"success": False, "error": f"快速失败: {str(e)}"}

调用:

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Fail-Fast Pattern 快速失败模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/6/30 7:15 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : FailFastBll.py
from FailFastPattern.api.order_controller import OrderController
from FailFastPattern.repository.external_services_repo import ExternalServices
from FailFastPattern.repository.inventory_repo import InventoryRepository
from FailFastPattern.service.order_service import OrderService
from FailFastPattern.service.validation_service import ValidationService

class FailFastBll(object):
    """

    """



    def demo(self):
        """

        :return:
        """
        # 初始化依赖
        inventory_repo = InventoryRepository()
        ext_services = ExternalServices()
        validation_service = ValidationService(inventory_repo, ext_services)
        order_service = OrderService(validation_service, inventory_repo, ext_services)
        controller = OrderController(order_service)

        print("==== 场景1:正常下单 ===")
        print(controller.create_jewelry_order("C1001", "DIA001", 1))

        print("\n==== 场景2:库存不足 ===")
        print(controller.create_jewelry_order("C1001", "DIA002", 1))

        print("\n==== 场景3:顾客无效 ===")
        print(controller.create_jewelry_order("C", "DIA001", 1))

        print("\n==== 场景4:支付服务挂了 ===")
        ext_services.payment_gateway = False
        print(controller.create_jewelry_order("C1001", "DIA001", 1))

输出:

哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)