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

推荐订阅源

www.infosecurity-magazine.com
www.infosecurity-magazine.com
D
DataBreaches.Net
T
Tailwind CSS Blog
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
F
Full Disclosure
V2EX - 技术
V2EX - 技术
N
News and Events Feed by Topic
Help Net Security
Help Net Security
L
LangChain Blog
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
Google Online Security Blog
Google Online Security Blog
P
Proofpoint News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
The Register - Security
The Register - Security
B
Blog RSS Feed
N
Netflix TechBlog - Medium
N
News | PayPal Newsroom
TaoSecurity Blog
TaoSecurity Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
V
Vulnerabilities – Threatpost
B
Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
I
Intezer
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
AI
AI
aimingoo的专栏
aimingoo的专栏
大猫的无限游戏
大猫的无限游戏
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cyberwarzone
Cyberwarzone
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
G
GRAHAM CLULEY
Vercel News
Vercel News
罗磊的独立博客
MyScale Blog
MyScale Blog
Last Week in AI
Last Week in AI
博客园 - 司徒正美
C
CERT Recently Published Vulnerability Notes
GbyAI
GbyAI
Scott Helme
Scott Helme
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Troy Hunt's Blog
A
About on SuperTechFans
P
Privacy International News Feed

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Sincronizando o Mercado Real: Consumindo a Brapi e Alimentando o Redis com Spring Boot
Roberto de V · 2026-04-27 · via DEV Community

Olá, pessoal!

Dando continuidade à série My Broker B3, hoje vamos falar sobre um componente essencial para o lado da B3 no nosso simulador: o B3 Market Sync API.

Antes de construirmos o motor que decide se uma ordem é executada ou rejeitada, precisamos garantir que ele tenha acesso a preços reais do mercado. É exatamente isso que o b3-market-sync-api faz: busca cotações reais de ativos brasileiros via brapi.dev e as armazena no Redis, pronto para consumo em tempo real.


🏗️ O que é o Market Sync?

Este microserviço tem uma responsabilidade única e bem definida: ser o produtor de dados de mercado do ecossistema. Ele opera de forma completamente assíncrona e independente — nenhum outro serviço precisa chamá-lo diretamente.

O fluxo é simples e elegante:

[brapi.dev] ◀── Feign Client ── [MarketSyncScheduler]
                                         │
                              market:price:{TICKER}
                                         │
                                      [Redis]
                                         │
                              [B3 Matching Engine] (próximo post)

Enter fullscreen mode Exit fullscreen mode


🎯 Foco no MVP

Neste serviço o objetivo é claro: ter preços reais disponíveis no Redis com baixa latência. O Matching Engine que construiremos no próximo post não vai consultar banco de dados nem fazer chamadas HTTP para obter preços — ele vai direto no Redis. Isso garante que a decisão de match aconteça em microssegundos.

Nesta fase, priorizei:

  • Sincronização agendada com guard de horário de pregão
  • Cache Redis com TTL para evitar dados obsoletos
  • Proteção de rate limit da API externa
  • Correção de bugs críticos encontrados na revisão
  • API REST para consulta dos preços em cache
  • Documentação via Swagger

🛠️ Stack Tecnológica

Tecnologia Uso
Java 21 + Spring Boot 3.5.11 Core do serviço
Spring Cloud OpenFeign Cliente HTTP declarativo para brapi.dev
Spring Data Redis Cache de alta performance
Spring Scheduling Sincronização periódica
Jackson JSR310 Suporte a tipos de data Java 8
SpringDoc OpenAPI Documentação via Swagger UI

🏗️ Os Pilares da Implementação

1. Feign Client — Consumindo a Brapi

O Spring Cloud OpenFeign permite declarar um cliente HTTP como uma simples interface, sem código boilerplate:

@FeignClient(name = "brapiClient", url = "${app.brapi.url}")
public interface BrapiClient {

    @GetMapping("/quote/{ticker}")
    BrapiResponseDTO getQuote(
        @PathVariable String ticker,
        @RequestParam String token
    );
}

Enter fullscreen mode Exit fullscreen mode

A URL e o token são injetados via application.yaml, mantendo o código limpo e configurável por ambiente.

2. Scheduler com Guard de Pregão

O coração do serviço é um job agendado que roda a cada 30 minutos. Mas antes de qualquer chamada à API, ele verifica se o mercado está aberto:

@Scheduled(fixedRateString = "${app.sync.interval:1800000}")
public void sync() {
    if (!isMarketOpen()) {
        log.info("Sync aborted: market is closed (outside trading hours or weekend).");
        return;
    }
    // ... busca e salva os preços
}

private boolean isMarketOpen() {
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Sao_Paulo"));
    DayOfWeek day = now.getDayOfWeek();
    int hour = now.getHour();

    if (day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY) {
        return false;
    }

    // B3 trading hours: 10:00 to 18:00 (Sao Paulo time)
    return hour >= 10 && hour < 18;
}

Enter fullscreen mode Exit fullscreen mode

Detalhe importante: usamos ZonedDateTime com America/Sao_Paulo explicitamente. Dentro de um container Docker, a JVM pode usar UTC por padrão — o que faria o guard de horário funcionar errado. Além disso, passamos -Duser.timezone=America/Sao_Paulo no ENTRYPOINT do Dockerfile para garantir que a JVM também respeite o timezone correto:

ENTRYPOINT ["java", "-Duser.timezone=America/Sao_Paulo", "-jar", "app.jar"]

Enter fullscreen mode Exit fullscreen mode

3. Cache Redis com TTL Correto

O MarketDataService salva cada cotação no Redis com uma chave padronizada e TTL de 5 minutos:

private static final Duration CACHE_TTL = Duration.ofMinutes(5);

public void saveToCache(BrapiResultDTO quote) {
    String key = CACHE_KEY_PREFIX + quote.getTicker();
    // TTL of 5 minutes — if sync stops, stale prices expire quickly
    // preventing the Matching Engine from using outdated data
    redisTemplate.opsForValue().set(key, quote, CACHE_TTL);
    log.info("Ticker {} updated in cache: R$ {}", quote.getTicker(), quote.getRegularMarketPrice());
}

Enter fullscreen mode Exit fullscreen mode

O TTL é fundamental: se o serviço cair, os preços expiram em 5 minutos. O Matching Engine passa a não encontrar o preço no Redis e rejeita as ordens — comportamento correto e previsível, muito melhor do que usar preços de horas atrás.

4. Deserialização do Timestamp Epoch

Um bug sutil que encontrei: a brapi.dev retorna o campo regularMarketTime como epoch Unix (número inteiro), mas o Jackson tentava desserializar como LocalDateTime (string ISO). Isso causa falha silenciosa na desserialização.

A solução foi criar um deserializer customizado:

public class EpochToLocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {

    private static final ZoneId SAO_PAULO = ZoneId.of("America/Sao_Paulo");

    @Override
    public LocalDateTime deserialize(JsonParser parser, DeserializationContext context)
            throws IOException {
        long epoch = parser.getLongValue();
        return LocalDateTime.ofInstant(Instant.ofEpochSecond(epoch), SAO_PAULO);
    }
}

Enter fullscreen mode Exit fullscreen mode

E anotá-lo no DTO:

@JsonDeserialize(using = EpochToLocalDateTimeDeserializer.class)
private LocalDateTime regularMarketTime;

Enter fullscreen mode Exit fullscreen mode

5. Proteção de Rate Limit

Como utilizamos o plano gratuito da brapi.dev, implementamos um delay entre as chamadas para evitar throttling:

for (String ticker : brapiProperties.getTickers()) {
    try {
        BrapiResponseDTO response = brapiClient.getQuote(ticker.trim(), brapiProperties.getToken());
        if (nonNull(response.getResults()) && !response.getResults().isEmpty()) {
            marketDataService.saveToCache(response.getResults().getFirst());
        }
        // Small delay between calls to avoid hitting rate limit on free plan
        Thread.sleep(200);
    } catch (Exception e) {
        log.error("Failed to sync ticker {}: {}", ticker, e.getMessage());
    }
}

Enter fullscreen mode Exit fullscreen mode

O try/catch por ticker é essencial — se um ativo falhar, o loop continua para os próximos.

6. API REST + Swagger

Embora o Matching Engine consuma os preços diretamente do Redis, adicionamos endpoints REST para facilitar debug e observabilidade:

Método Endpoint Descrição
GET /api/v1/quotes Lista preços de todos os tickers configurados
GET /api/v1/quotes/{ticker} Retorna o preço de um ticker específico

Documentados via Swagger UI em http://localhost:8096/swagger-ui.html.


🔒 Segurança — Token Fora do Código

Um problema crítico que corrigi: o token da brapi.dev estava hardcoded como valor padrão no application.yaml:

# ❌ Antes — token exposto no repositório público
token: ${BRAPI_TOKEN:mFk3HMLijAtxsP5y1ZjhsY}

# ✅ Depois — sem fallback, variável obrigatória
token: ${BRAPI_TOKEN}

Enter fullscreen mode Exit fullscreen mode

Nunca exponha credenciais com valores default em repositórios públicos. A aplicação agora falha na inicialização se a variável não for fornecida — comportamento correto.


✅ Validando a Execução

Com a aplicação rodando localmente:

  • ✅ Tomcat subiu na porta 8096
  • ✅ Aplicação inicializou em menos de 3 segundos
  • ✅ Scheduler disparou e exibiu: Sync aborted: market is closed (outside trading hours or weekend)
  • ✅ Swagger UI acessível em http://localhost:8096/swagger-ui.html

🚀 O que vem a seguir?

Com o b3-market-sync-api pronto e alimentando o Redis com preços reais, temos a base que o próximo serviço precisa para funcionar. No próximo post vamos construir o B3 Matching Engine — o motor que vai consumir esses preços e decidir se as ordens da corretora serão executadas ou rejeitadas.

Ficou com alguma dúvida sobre a integração com Redis ou sobre o guard de horário de pregão? Deixe nos comentários!


🔎 Sobre a série

⬅️ Post Anterior: Do Stream para o Banco: Processando Market Data com Spring Boot, Redis e Flyway

➡️ Próximo Post: O Coração da B3: Construindo o Matching Engine com RabbitMQ e Redis (em breve)

📘 Índice da Série: Guia da Série


Links: