热门角色不仅是灵感来源,更是你的效率助手。通过精挑细选的角色提示词,你可以快速生成高质量内容、提升创作灵感,并找到最契合你需求的解决方案。让创作更轻松,让价值更直接!
我们根据不同用户需求,持续更新角色库,让你总能找到合适的灵感入口。
本提示词专为后端开发场景设计,能够为提供的代码片段生成精准、清晰的技术性内联注释。通过深度分析代码逻辑和功能结构,自动生成符合技术文档标准的注释内容,帮助开发人员快速理解代码意图、提高代码可维护性。支持多种编程语言和复杂业务逻辑的注释生成,确保注释内容与代码功能完全匹配,避免冗余信息,提升团队协作效率。
代码语言:Java
注释位置:
package com.example.order;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 订单创建的HTTP入口控制器。
* 暴露 /orders POST 接口,负责最小化输入校验与请求转发到业务服务层。
*/
@RestController
@RequestMapping("/orders")
public class OrderController {
// 注入订单服务,承载业务逻辑(控制器保持“薄”)
private final OrderService service;
public OrderController(OrderService service){ this.service = service; }
/**
* 创建订单接口:
* - 接收JSON请求体并反序列化为 OrderRequest
* - 检查 items 基本有效性
* - 生成请求级追踪ID(requestId)用于事件链路关联
* - 调用服务层创建订单并返回201响应
*/
@PostMapping
public ResponseEntity<OrderResponse> create(@RequestBody OrderRequest req){
// 基础参数校验:要求请求存在且包含至少一个明细项
// 说明:仅校验 items 非空与非空列表,未在此处校验价格/数量的取值范围
if(req == null || req.getItems() == null || req.getItems().isEmpty()){
throw new IllegalArgumentException("items required");
}
// 为当前请求生成唯一追踪ID,以便后续事件/日志进行跨组件关联
UUID requestId = UUID.randomUUID();
// 委托服务层执行业务处理(金额计算、持久化、事件发布)
OrderResponse res = service.create(req, requestId);
// 返回201 Created,并携带订单标识与汇总金额
return ResponseEntity.status(HttpStatus.CREATED).body(res);
}
}
/**
* 订单业务服务:
* - 计算订单总金额(使用BigDecimal避免浮点误差)
* - 构造并持久化订单
* - 发布订单创建事件(携带请求追踪ID)
*/
class OrderService {
// 仓储端口:隐藏具体持久化技术细节
private final OrderRepository repo;
// 事件总线:实现与下游/异步处理的解耦
private final EventBus eventBus;
public OrderService(OrderRepository repo, EventBus eventBus){
this.repo = repo; this.eventBus = eventBus;
}
/**
* 创建订单的核心流程。
* @param req 订单请求,包含客户ID与明细项
* @param requestId 本次调用生成的追踪ID,用于事件链路关联
* @return 订单响应(订单ID与总金额)
*/
public OrderResponse create(OrderRequest req, UUID requestId){
// 汇总订单总金额:
// - 明细项映射为 price * qty(将数量转换为BigDecimal参与精确计算)
// - 使用 reduce 自 BigDecimal.ZERO 累加,保证空列表时有幺元(但外层已保证非空)
BigDecimal total = req.getItems().stream()
.map(i -> i.getPrice().multiply(BigDecimal.valueOf(i.getQty())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
// 构造订单聚合根,生成订单ID与创建时间,用于业务追踪与数据一致性
Order o = new Order();
o.setId(UUID.randomUUID());
o.setCustomerId(req.getCustomerId());
o.setTotal(total);
o.setCreatedAt(Instant.now());
// 将订单持久化;具体存储介质与事务策略由仓储实现决定
repo.save(o);
// 发布领域事件,携带订单ID与请求追踪ID,便于异步消费者进行幂等/关联处理
eventBus.publish(new OrderCreatedEvent(o.getId(), requestId));
// 返回轻量响应对象,仅包含前端关心的标识与金额信息
return new OrderResponse(o.getId(), total);
}
}
/**
* 订单仓储端口:定义持久化能力的抽象。
* 具体实现可基于JPA、MyBatis或其他存储方案。
*/
interface OrderRepository { void save(Order o); }
/**
* 事件总线端口:用于将领域事件分发至异步处理通道。
* 具体实现可对接消息队列或应用内事件机制。
*/
interface EventBus { void publish(Object evt); }
/**
* 订单创建请求DTO:
* - customerId:下单客户标识
* - items:订单明细项集合
* 由Spring MVC根据请求体自动反序列化。
*/
class OrderRequest {
private String customerId;
private List<Item> items;
public String getCustomerId(){ return customerId; }
public void setCustomerId(String id){ this.customerId = id; }
public List<Item> getItems(){ return items; }
public void setItems(List<Item> items){ this.items = items; }
}
/**
* 订单明细项:
* - price:单价(BigDecimal保证金额精度)
* - qty:数量(整型数量,计算时转换为BigDecimal参与乘法)
*/
class Item {
private BigDecimal price;
private int qty;
public BigDecimal getPrice(){ return price; }
public void setPrice(BigDecimal p){ this.price = p; }
public int getQty(){ return qty; }
public void setQty(int q){ this.qty = q; }
}
/**
* 订单实体:
* - id:订单唯一标识
* - customerId:客户标识
* - total:订单总金额(明细汇总)
* - createdAt:订单创建时间(UTC时间戳)
*/
class Order {
private UUID id;
private String customerId;
private BigDecimal total;
private Instant createdAt;
public UUID getId(){ return id; }
public void setId(UUID id){ this.id = id; }
public String getCustomerId(){ return customerId; }
public void setCustomerId(String id){ this.customerId = id; }
public BigDecimal getTotal(){ return total; }
public void setTotal(BigDecimal t){ this.total = t; }
public Instant getCreatedAt(){ return createdAt; }
public void setCreatedAt(Instant t){ this.createdAt = t; }
}
/**
* 订单创建响应:
* 使用Java 16+ record 定义不可变响应载体,仅包含订单ID与总金额。
*/
record OrderResponse(UUID id, BigDecimal total){}
/**
* 订单创建事件:
* - orderId:被创建的订单ID
* - requestId:触发该事件的请求追踪ID(用于日志/消息关联)
*/
class OrderCreatedEvent {
private final UUID orderId;
private final UUID requestId;
public OrderCreatedEvent(UUID orderId, UUID requestId){
this.orderId = orderId; this.requestId = requestId;
}
}
注释说明:
技术要点:
代码语言:Python (FastAPI)
注释位置:
from fastapi import FastAPI, Header, HTTPException
from typing import Optional
import time
app = FastAPI()
# Process-wide in-memory cache for user profiles.
# Keyed by "profile:{user_id}", persists for the lifetime of the process.
# No TTL/eviction and no synchronization across workers.
cache = {}
def verify_token(token: str) -> dict:
"""
Parse and minimally validate a JWT-like token.
- Splits the token on '.' to check for structure; raises ValueError if malformed.
- Derives the 'sub' (subject/user identifier) from the first segment.
- Sets a synthetic 'exp' (expiry) to current time + 600 seconds.
- Returns claims as a dict; no signature verification or decoding performed.
"""
parts = token.split(".")
if len(parts) < 2:
# Token structure check: requires at least header and payload segments.
# Error propagates to the caller; not transformed into HTTPException here.
raise ValueError("invalid")
return {"sub": parts[0], "exp": time.time() + 600}
def load_user(user_id: str) -> dict:
"""
Retrieve a user profile for the given user_id.
Placeholder for data access: returns a deterministic profile shape
with a static 'roles' list.
"""
return {"id": user_id, "name": f"user-{user_id}", "roles": ["reader"]}
@app.get("/users/{user_id}")
def get_user(user_id: str, authorization: Optional[str] = Header(None)):
"""
REST endpoint to fetch a user profile with auth and simple caching.
Request:
- Path parameter 'user_id' identifies the target profile.
- 'Authorization' header is expected (Bearer token format).
Flow:
1) Validate presence of Authorization header; return 401 if missing.
2) Extract token string from the header (naive 'Bearer ' removal).
3) Verify token and obtain claims; ValueError from verify_token will propagate.
4) Attempt to serve profile from in-memory cache; populate on miss.
5) Enforce access rule: claims['sub'] must equal requested user_id.
6) Return profile and a 'cached' flag indicating cache usage.
"""
if not authorization:
# Missing credentials: signal authentication required.
raise HTTPException(status_code=401, detail="missing auth")
# Naive Bearer token extraction: removes leading "Bearer " if present.
# Does not enforce case or exact scheme; remaining string treated as token.
token = authorization.replace("Bearer ", "")
# Token verification; produces claims dict with 'sub' and 'exp'.
# Note: 'exp' is not checked here; only 'sub' is used for authorization.
claims = verify_token(token)
# Build cache key for the requested profile.
cache_key = f"profile:{user_id}"
# Read-through cache: serve from cache if present, otherwise load and store.
if cache_key in cache:
profile = cache[cache_key]
cached = True
else:
profile = load_user(user_id)
cache[cache_key] = profile
cached = False
# Authorization check: only allow access if the token subject matches the path user_id.
if claims["sub"] != user_id:
# Authenticated but not authorized for this resource.
raise HTTPException(status_code=403, detail="forbidden")
# Response payload includes the profile and whether it was served from cache.
return {"profile": profile, "cached": cached}
注释说明:
技术要点:
代码语言:JavaScript (Node.js/Express)
注释位置:
const express = require('express');
const app = express();
/**
* 创建基于令牌桶算法的限流中间件工厂。
* - 按 IP 维度进行限流,每分钟允许 ratePerMin 次请求(桶容量等于速率)。
* - 使用内存 Map 保存每个 IP 的令牌桶状态:{ tokens, updated }。
* - 每整分钟补充令牌,令牌数不超过桶容量。
*/
function createLimiter(ratePerMin){
// 保存各 IP 的令牌桶;key 为 req.ip,value 为 { tokens: 剩余令牌数, updated: 上次更新时间戳 }
const tokens = new Map();
// 返回 Express 中间件函数,用于在请求进入业务处理前执行限流判断
return function limiter(req, res, next){
// 使用请求来源 IP 作为限流键;与部署环境的代理配置和 req.ip 获取方式相关
const key = req.ip;
const now = Date.now();
// 若不存在历史记录则初始化桶为满额;否则读取现有桶状态
const bucket = tokens.get(key) || { tokens: ratePerMin, updated: now };
// 计算距上次更新的时间间隔(毫秒)
const elapsed = now - bucket.updated;
// 按整分钟补充令牌:每经过 60000ms 补充 ratePerMin 个令牌
const refill = Math.floor(elapsed / 60000) * ratePerMin;
// 更新令牌数并限制最大不超过桶容量(防止无限累积)
bucket.tokens = Math.min(ratePerMin, bucket.tokens + refill);
// 将更新时间设置为当前时刻(与按整分钟补充策略配合)
bucket.updated = now;
// 若令牌不足(<= 0),直接返回 429 状态码,拒绝当前请求
if (bucket.tokens <= 0){
res.status(429).json({ error: "too many requests" });
return;
}
// 消耗一个令牌,允许请求继续进入后续中间件/路由
bucket.tokens -= 1;
// 持久化当前 IP 的最新桶状态到内存 Map
tokens.set(key, bucket);
// 进入后续处理链
next();
};
}
// 解析入站请求的 JSON 正文,供业务路由使用
app.use(express.json());
// 全局应用限流中间件:每个 IP 每分钟最多 60 次请求
app.use(createLimiter(60));
/**
* 支付创建接口:
* - 接收 JSON 请求体中的 amount、currency 字段。
* - 校验必填字段,缺失则返回 400。
* - 模拟异步处理(延时 50ms),成功则返回 201 和生成的支付 ID。
*/
app.post('/payments', async (req, res) => {
// 解构获取业务参数;若 body 不存在则使用空对象避免解构报错
const { amount, currency } = req.body || {};
// 基础校验:要求存在 amount 和 currency(仅校验存在性,不校验类型和范围)
if (!amount || !currency){
res.status(400).json({ error: "invalid payload" });
return;
}
// 生成简易的支付 ID(基于随机字符串);用于示例,不保证强唯一性
const id = Math.random().toString(36).slice(2);
// 模拟异步处理耗时,例如调用第三方支付网关或数据库操作
await new Promise(r => setTimeout(r, 50));
// 创建成功返回 201 状态码,并携带支付 ID 与状态
res.status(201).json({ paymentId: id, status: "created" });
});
// 启动 HTTP 服务,监听 3000 端口
app.listen(3000);
注释说明:
技术要点:
让后端团队以极低成本获得“可直接合入”的高质量内联注释,具体目标包括:
在提交代码前一键生成精准注释,清楚标记业务意图、边界条件和异常处理;提高可读性与交接效率,减少后续答疑。
快速理解变更点与数据流,定位风险与关键逻辑;用统一注释规范提升评审效率,缩短合并请求往返次数。
为核心模块生成结构化说明,梳理依赖与影响范围;用于设计评审、重构规划和版本发布说明。
将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。
把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。
在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。
半价获取高级提示词-优惠即将到期