Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
from fastapi.concurrency import run_in_threadpool
async def execute(data: DataRequest) -> DataResponse:
try:
result = await run_in_threadpool(sync_function, data)
return DataResponse(data=result)
except Exception as e:
return DataResponse(
error=str(e),
success=False,
)
В общем работает нормально. Для всех вызовов под капотом используется общий тредпул, всё работает предсказуемо.
Но потребовалось изменить количество запускаемых в пуле потоков (по умолчанию создается 40 воркеров).
Так как дело происходит с FastAPI, делается это через lifespan используя настройки anyio:
import anyio
@asynccontextmanager
async def lifespan(app: FastAPI):
limiter = anyio.to_thread.current_default_thread_limiter()
limiter.total_tokens = 100
yield
# если вдруг нужно вернуть обратно
limiter.total_tokens = 40
Зачем менять количество воркеров?
- уменьшить, если оперативки мало (один тред занимает ~8мб)
- увеличить чтобы выдержать нагрузку
Если есть предложения получше при тех же вводных - предлагайте😉
#async
#java#docker#mybatis#oss#springboot#vue
RuoYi-Vue-Plus is a free, open-source backend framework upgraded from RuoYi for distributed clusters and multi-tenant use, built with Spring Boot 3.5, Vue3, TypeScript, MyBatis-Plus, and Redisson. It offers superior features like plugin decoupling, advanced permissions, multi-database support, workflows, code generation, Docker deployment, monitoring, and data security tools—far beyond original RuoYi. You benefit by building scalable enterprise apps 80% faster with less code, easier maintenance, and robust security for production. Warning: Versions ≤5.5.3 have critical flaws (CVE-2025-66916 RCE, CVE-2026-2819 auth bypass); update immediately.
https://github.com/dromara/RuoYi-Vue-Plus
#SpringBoot#RESTAPI#BackendDevelopment#CodeWithMosh#Java#StripeIntegration#CloudDeployment#LearnToCode
🚀 Ready to take your backend skills to the next level?
🔗Spring Boot: Mastering REST API Development🎓
- Learn to build clean, secure RESTful APIs
- Add authentication, role-based access, and JWT security 🔒
- Integrate Stripe for real payment processing 💳
- Deploy your app and database to the cloud ☁️
- Apply industry best practices for production-ready code 🛠
👉 Join now @repo_science and start building real-world projects like a pro!
#javascript#approval_process#cms#crm#ehr#erp#hr#layui#mysql#oa#privileges#redis#skyeye#springboot#springboot2#springcloud_vue#websocket
This platform uses Springboot, Layui, UNI-APP, and Ant Design Vue to create a low-code system for intelligent manufacturing. It includes over 30 application modules and more than 50 electronic workflows, covering CRM, ERP, MES, and more. This system streamlines business processes from customer relations to production and after-sales service, improving efficiency and data transparency. It also manages employee operations, providing a comprehensive solution for businesses. The benefits include faster development, reduced redundancy, and enhanced data management, making it ideal for companies seeking digital transformation.
https://github.com/dromara/skyeye