热门角色不仅是灵感来源,更是你的效率助手。通过精挑细选的角色提示词,你可以快速生成高质量内容、提升创作灵感,并找到最契合你需求的解决方案。让创作更轻松,让价值更直接!
我们根据不同用户需求,持续更新角色库,让你总能找到合适的灵感入口。
本提示词专为后端开发场景设计,能够根据功能描述自动生成专业、规范的README文档章节。它采用技术文档写作风格,确保内容精确清晰、结构逻辑严谨,涵盖功能概述、技术实现、使用方法和配置说明等核心要素。通过系统化的文档生成流程,帮助开发者快速创建高质量的技术文档,提升项目可维护性和团队协作效率。适用于API接口、数据库模块、系统组件等多种后端功能的文档编写需求。
该模块提供基于 JWT 的用户鉴权与令牌发放能力,面向后端服务与前端应用的登录、令牌刷新与退出场景。功能重点包括:
认证与加密
鉴权与授权
会话与黑名单
安全与合规
解耦设计
运维与监控
接口列表
登录接口
刷新令牌
退出注销
访问受保护接口
角色与权限校验
错误处理
IP 绑定与设备指纹
环境变量/配置项
application.yml 示例 auth: jwt: secret: ${AUTH_JWT_SECRET} token-ttl: ${TOKEN_TTL} refresh-ttl: ${REFRESH_TTL} security: cors: allowed-origins: ${CORS_ALLOWED_ORIGINS} rate-limit: per-min: ${RATE_LIMIT_PER_MIN} cookie: secure: ${COOKIE_SECURE}
.env 模板示例(用于本地开发) AUTH_JWT_SECRET=please_change_me TOKEN_TTL=15 REFRESH_TTL=7 CORS_ALLOWED_ORIGINS=http://localhost:3000 RATE_LIMIT_PER_MIN=60 COOKIE_SECURE=false
部署与运维
cURL 调用
登录
curl -X POST https://api.example.com/auth/login
-H "Content-Type: application/json"
-d '{ "username": "alice", "password": "s3cr3t" }'
响应: { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "refresh_token": "r1...or_jwt", "token_type": "Bearer", "expires_in": 900 }
刷新令牌
curl -X POST https://api.example.com/auth/refresh
-H "Content-Type: application/json"
-d '{ "refresh_token": "r1...or_jwt" }'
退出注销
curl -X POST https://api.example.com/auth/logout
-H "Content-Type: application/json"
-d '{ "refresh_token": "r1...or_jwt" }'
访问受保护资源
curl -X GET https://api.example.com/orders
-H "Authorization: Bearer eyJhbGciOiJIUzI1Ni..."
Spring Boot 控制器权限示例(基于注解) // 受保护接口示例,需角色 ROLE_ADMIN @GetMapping("/admin/reports") @PreAuthorize("hasRole('ADMIN')") public Report list() { ... }
// 细粒度权限示例,根据 claims 中的权限集合判断 @PostMapping("/orders") @PreAuthorize("@perm.hasPermission(authentication, 'ORDER_CREATE')") public Order create(@RequestBody CreateOrderRequest req) { ... }
鉴权拦截器校验示例(伪代码) public void doFilter(req, res, chain) { String auth = req.getHeader("Authorization"); if (auth == null || !auth.startsWith("Bearer ")) { throw new AuthException("AUTH_401_INVALID"); } String jwt = auth.substring(7); Claims claims = jwtService.parseAndValidate(jwt, AUTH_JWT_SECRET); // 过期校验、签名校验 // 可选:IP/设备指纹一致性校验 // 可选:黑名单校验(根据 jti) SecurityContext.setAuthenticatedUser(claims); chain.doFilter(req, res); }
令牌生成示例(伪代码) String accessToken = jwtService.sign( Map.of( "sub", userId, "roles", roles, "permissions", permissions, "ip", requestIp // 如启用 ), AUTH_JWT_SECRET, Duration.ofMinutes(TOKEN_TTL) );
String refreshToken = refreshService.issueRefreshToken(userId, Duration.ofDays(REFRESH_TTL));
密钥管理
TTL 与会话策略
安全与合规
CORS 与前端集成
IP 绑定与设备指纹
监控与运维
依赖与解耦
REST API
{
"id": "ord_123",
"userId": "u_001",
"status": "PENDING",
"amount": 199.00,
"currency": "CNY",
"items": [{"sku":"sku-1001","quantity":2}],
"sagaState": "PENDING",
"createdAt": "2025-12-01T08:00:00Z"
}
{
"id": "ord_123",
"userId": "u_001",
"status": "COMPLETED",
"amount": 199.00,
"currency": "CNY",
"items": [{"sku":"sku-1001","quantity":2}],
"views": {
"inventory": {"reserved": true, "reservationId": "res_789"},
"payment": {"status": "SUCCEEDED", "paymentId": "pay_456"},
"notification": {"sent": true, "channel": "email"}
},
"updatedAt": "2025-12-01T08:05:00Z",
"cache": {"hit": false, "ttlMs": 0}
}
事件接口(Kafka)
{
"eventVersion": 1,
"idempotencyKey": "idem-abc-123",
"correlationId": "corr-xyz-456",
"timestamp": "2025-12-01T08:00:00Z",
"type": "order.created", // 或 inventory.reserved / payment.succeeded
"data": {
// 按事件类型携带的业务数据
}
}
{
"orderId": "ord_123",
"userId": "u_001",
"amount": 199.00,
"currency": "CNY",
"items": [{"sku":"sku-1001","quantity":2}]
}
{
"orderId": "ord_123",
"reservationId": "res_789",
"reserved": true
}
{
"orderId": "ord_123",
"paymentId": "pay_456",
"status": "SUCCEEDED"
}
Gin 路由与中间件(示例代码为简化版本,省略错误处理与依赖注入)
package main
import (
"context"
"net/http"
"os"
"time"
"github.com/gin-gonic/gin"
)
// 简化的服务接口
type OrderService interface {
CreateOrder(ctx context.Context, req CreateOrderRequest) (Order, error)
GetOrder(ctx context.Context, id string, opts QueryOptions) (AggregatedOrderView, error)
ListOrdersByUser(ctx context.Context, userId string, page, pageSize int) ([]Order, error)
}
// 请求与响应模型(示意)
type CreateOrderRequest struct {
UserId string `json:"userId" binding:"required"`
Items []OrderItem `json:"items" binding:"required"`
Amount float64 `json:"amount" binding:"required"`
Currency string `json:"currency" binding:"required"`
Metadata map[string]any `json:"metadata"`
IdempotencyKey string `json:"-"` // 从 Header 注入
}
type OrderItem struct {
SKU string `json:"sku"`
Quantity int `json:"quantity"`
}
type QueryOptions struct {
IncludeDetails bool
CacheOnly bool
}
func main() {
r := gin.New()
r.Use(gin.Recovery())
r.Use(correlationMiddleware()) // 注入/传播 X-Correlation-Id
r.Use(metricsMiddleware()) // 指标采集(示意)
r.Use(loggingMiddleware()) // 结构化日志(示意)
svc := newOrderService() // 注入真实实现
// 健康与就绪
r.GET("/health", func(c *gin.Context) { c.Status(http.StatusOK) })
r.GET("/ready", func(c *gin.Context) {
// 检查数据库、Kafka 客户端是否就绪(示意)
c.Status(http.StatusOK)
})
// 订单创建
r.POST("/orders", func(c *gin.Context) {
var req CreateOrderRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
return
}
req.IdempotencyKey = c.GetHeader("Idempotency-Key")
// 超时控制
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
order, err := svc.CreateOrder(ctx, req)
if err != nil {
// 根据错误类型返回 409/500 等(简化)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, order)
})
// 单订单查询
r.GET("/orders/:id", func(c *gin.Context) {
id := c.Param("id")
include := c.DefaultQuery("includeDetails", "true") == "true"
cacheOnly := c.DefaultQuery("cacheOnly", "false") == "true"
opts := QueryOptions{IncludeDetails: include, CacheOnly: cacheOnly}
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
defer cancel()
view, err := svc.GetOrder(ctx, id, opts)
if err != nil {
// 简化错误映射
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, view)
})
// 用户订单列表
r.GET("/orders", func(c *gin.Context) {
userId := c.Query("userId")
if userId == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "userId required"})
return
}
// 简化分页
page, pageSize := 1, 20
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
defer cancel()
list, err := svc.ListOrdersByUser(ctx, userId, page, pageSize)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": list, "page": page, "pageSize": pageSize})
})
port := os.Getenv("SERVICE_PORT")
if port == "" {
port = "8080"
}
r.Run(":" + port)
}
// 以下中间件为示意,实际实现需结合日志与追踪框架
func correlationMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
corr := c.GetHeader("X-Correlation-Id")
if corr == "" {
corr = generateCorrelationID()
}
c.Set("correlationId", corr)
c.Writer.Header().Set("X-Correlation-Id", corr)
c.Next()
}
}
func metricsMiddleware() gin.HandlerFunc { return func(c *gin.Context) { c.Next() } }
func loggingMiddleware() gin.HandlerFunc { return func(c *gin.Context) { c.Next() } }
func generateCorrelationID() string { return time.Now().Format("20060102T150405.000000000") }
Saga 编排与事件处理(示意)
// 订单创建 Saga 简化伪代码
func (s *orderService) CreateOrder(ctx context.Context, req CreateOrderRequest) (Order, error) {
// 1. 幂等:检查/记录 Idempotency-Key
if exists, err := s.idemRepo.Exists(req.IdempotencyKey); err != nil {
return Order{}, err
} else if exists {
return s.idemRepo.GetOrderByKey(req.IdempotencyKey)
}
// 2. 创建订单(状态 PENDING)
order, err := s.orderRepo.CreatePending(req)
if err != nil { return Order{}, err }
// 3. 预留库存(带超时与熔断)
if err := s.cbInventory.Do(func() error {
return s.inventoryClient.Reserve(ctx, order.ID, req.Items)
}); err != nil {
// 补偿:取消订单
_ = s.orderRepo.MarkCancelled(order.ID, "inventory_reserve_failed")
return Order{}, err
}
_ = s.orderRepo.UpdateSagaState(order.ID, "INVENTORY_RESERVED")
// 4. 发起支付
if err := s.cbPayment.Do(func() error {
return s.paymentClient.Pay(ctx, order.ID, req.Amount, req.Currency)
}); err != nil {
// 补偿:释放库存 + 取消订单
_ = s.inventoryClient.Release(ctx, order.ID)
_ = s.orderRepo.MarkCancelled(order.ID, "payment_failed")
return Order{}, err
}
_ = s.orderRepo.UpdateSagaState(order.ID, "PAYMENT_INITIATED")
// 5. 发布 order.created 事件
_ = s.eventBus.Publish("order.created", Event{
Version: 1, IdempotencyKey: req.IdempotencyKey, CorrelationID: getCorr(ctx),
Data: map[string]any{"orderId": order.ID, "userId": req.UserId, "amount": req.Amount, "currency": req.Currency, "items": req.Items},
})
return s.orderRepo.Get(order.ID)
}
// 事件消费者:inventory.reserved / payment.succeeded
func (c *consumer) OnMessage(msg KafkaMessage) {
// 幂等检查:基于 idempotencyKey + eventVersion
if c.processed.IsProcessed(msg.IdempotencyKey, msg.EventVersion) { return }
switch msg.Type {
case "inventory.reserved":
// 更新订单状态为 INVENTORY_RESERVED(若支付已成功则推进完成)
_ = c.orderRepo.UpdateSagaState(msg.Data["orderId"].(string), "INVENTORY_RESERVED")
case "payment.succeeded":
orderID := msg.Data["orderId"].(string)
_ = c.orderRepo.UpdateStatus(orderID, "COMPLETED")
_ = c.notifyClient.Send(orderID) // 通知(示意)
}
c.processed.MarkProcessed(msg.IdempotencyKey, msg.EventVersion)
}
聚合查询与缓存/熔断(示意)
func (s *orderService) GetOrder(ctx context.Context, id string, opts QueryOptions) (AggregatedOrderView, error) {
base, err := s.orderRepo.Get(id)
if err != nil { return AggregatedOrderView{}, err }
if !opts.IncludeDetails {
return AggregatedOrderView{Order: base}, nil
}
if opts.CacheOnly {
if v, ok := s.cache.Get(id); ok { return v, nil }
return AggregatedOrderView{}, ErrCacheMiss
}
// 并行调用下游 + 超时 + 熔断
type result struct { name string; data any; err error }
ch := make(chan result, 3)
go func() { ch <- callWithCB(ctx, "inventory", s.cbInventory, func() (any, error) { return s.inventoryClient.View(ctx, id) }) }()
go func() { ch <- callWithCB(ctx, "payment", s.cbPayment, func() (any, error) { return s.paymentClient.View(ctx, id) }) }()
go func() { ch <- callWithCB(ctx, "notify", s.cbNotify, func() (any, error) { return s.notifyClient.View(ctx, id) }) }()
view := AggregatedOrderView{Order: base}
timeout := time.After(1500 * time.Millisecond)
completed := 0
for completed < 3 {
select {
case r := <-ch:
completed++
if r.err == nil {
switch r.name {
case "inventory": view.Inventory = r.data
case "payment": view.Payment = r.data
case "notify": view.Notification = r.data
}
}
case <-timeout:
// 超时:尝试返回缓存
if v, ok := s.cache.Get(id); ok { return v, nil }
return AggregatedOrderView{}, context.DeadlineExceeded
}
}
s.cache.Set(id, view, ttlFromConfig())
return view, nil
}
Kubernetes 示例(示意,需根据实际镜像与命名空间调整)
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-aggregator
spec:
replicas: 2
selector:
matchLabels:
app: order-aggregator
template:
metadata:
labels:
app: order-aggregator
spec:
containers:
- name: app
image: your-registry/order-aggregator:latest
ports:
- containerPort: 8080
env:
- name: SERVICE_PORT
value: "8080"
- name: KAFKA_BROKERS
value: "kafka-0:9092,kafka-1:9092"
- name: DB_URL
valueFrom:
secretKeyRef:
name: order-db-secret
key: url
- name: CB_FAILURE_RATE
value: "0.5"
- name: RETRY_BACKOFF_MS
value: "200"
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 5
---
apiVersion: v1
kind: Service
metadata:
name: order-aggregator
spec:
selector:
app: order-aggregator
ports:
- port: 80
targetPort: 8080
protocol: TCP
name: http
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: order-aggregator-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: order-aggregator
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
准备目录结构
基本命令
命令示例
回滚说明
数据脱敏与影子表
时间分区与索引维护
流水线集成(示例)
迁移脚本示例(创建表与索引)
回滚脚本示例(与上面版本匹配)
种子数据示例
影子表切换示例(抽象示意)
时间分区示例(抽象示意)
如需扩展或定制(例如报告格式、额外命令、告警集成),请在工具仓库的配置与脚本约定范围内实现,并遵循上述安全与版本规范。
将后端功能说明快速转化为可发布的README文档,让“写文档”从耗时琐事变成高效产出。通过标准化章节与清晰表达,覆盖接口、数据库、系统组件、微服务、工具库等常见场景,帮助团队在立项、联调、交付与运维阶段持续生成一致、易读、可复用的技术说明。目标是显著提升交付效率与协作质量,减少口头解释与反复沟通,用几分钟产出一份专业文档,试用即见成效,加速从体验到付费的转化。
从简要功能描述一键生成规范README,包含场景说明、使用步骤与配置提示,当天即可提交合并,减少文档返工与代码沟通成本
快速为新模块统一文档口径,明确边界与依赖,用于评审与交付时的权威参考,提升跨团队协同与新人入项效率
获得部署与配置要点的清晰说明,按自检清单逐项核对,减少环境差异带来的故障,提高上线稳定性与回滚效率
将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。
把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。
在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。
半价获取高级提示词-优惠即将到期