
介绍
对于专注于构建有效且可扩展的微服务的 java 开发人员来说,掌握 api 设计至关重要。本文概述了增强编码技能的最佳实践,并使用 java 示例来说明有效的技术与常见的错误。
1. 坚持restful原则
restful 架构依赖于无状态、可缓存性和统一接口等原则,促进一致的交互。
好示例:使用 post 请求创建新资源。
@restcontroller@requestmapping("/products")public class productcontroller { @postmapping public responseentity createproduct(@requestbody product product) { product savedproduct = productservice.save(product); return responseentity.status(httpstatus.created).body(savedproduct); }}
避免示例:使用 delete 请求检索资源。
@restcontroller@requestmapping("/products")public class productcontroller { @deletemapping("/{id}") public responseentity getproduct(@pathvariable long id) { // incorrect; delete should not be used for retrieval. product product = productservice.findbyid(id); return responseentity.ok(product); }}
2. 使用适当的 http 状态代码
http 状态代码对于向客户端传达请求结果至关重要。
好示例:成功删除资源时返回 204 no content。
@deletemapping("/{id}")public responseentity deleteproduct(@pathvariable long id) { productservice.deletebyid(id); return responseentity.nocontent().build();}
避免 示例:由于资源不存在而导致删除失败,返回 200 ok。
@deletemapping("/{id}")public responseentity deleteproduct(@pathvariable long id) { if (!productservice.existsbyid(id)) { return responseentity.ok().build(); // misleading response. } productservice.deletebyid(id); return responseentity.nocontent().build();}
3. 实施 api 版本控制
api 版本控制有助于在不中断现有用户的情况下管理变更,从而实现平稳过渡和更新。
立即学习“Java免费学习笔记(深入)”;
好示例:为了清楚起见,在 uri 中使用版本。
@restcontroller@requestmapping("/api/v2/orders")public class ordercontroller { // actions specific to version 2 of the orders api.}
避免示例:没有版本控制,这可能会破坏客户端实现。
@restcontroller@requestmapping("/orders")public class ordercontroller { // no versioning in place; risky for clients.}
4. 优雅地处理异常
有效的错误处理通过提供有意义的错误消息来增强用户体验。
好示例:无效输入场景的自定义异常处理程序。
@exceptionhandler(invalidinputexception.class)public responseentity handleinvalidinput(invalidinputexception ex) { return responseentity.badrequest().body(ex.getmessage());}
避免示例:返回缺乏详细信息的通用错误消息。
@exceptionhandler(exception.class)public responseentity handleallerrors(exception ex) { // bad practice; vague error message is unhelpful. return responseentity.status(httpstatus.internal_server_error).body("error occurred");}
5. api 设计中优先考虑安全性
安全至关重要; api 应强制执行身份验证和授权以保护敏感数据。
好示例:在访问资源之前检查用户权限。
@getmapping("/orders/{id}")public responseentity getorderbyid(@pathvariable long id) { if (!authservice.haspermission("view_order", id)) { return responseentity.status(httpstatus.forbidden).build(); } order order = orderservice.findbyid(id); return order != null ? responseentity.ok(order) : responseentity.notfound().build();}
避免示例:忽视授权检查,面临未经授权访问的风险。
@getmapping("/orders/{id}")public responseentity getorderbyid(@pathvariable long id) { // missing permission check; poses a security risk. order order = orderservice.findbyid(id); return responseentity.ok(order);}
6. 维护清晰的 api 文档
完整的文档可以帮助开发人员了解如何有效地使用 api,从而促进集成的简便性。
好示例:使用 openapi 注释来获得清晰的文档。
设计师AI工具箱
最懂设计师的效率提升平台,实现高效设计出图和智能改图,室内设计,毛坯渲染,旧房改造 ,软装设计
124 查看详情
@api(tags = "order management")@restcontroller@requestmapping("/api/v1/orders")public class ordercontroller { // actions documented with openapi annotations.}
避免示例:缺乏文档,导致 api 难以导航。
@restcontroller@requestmapping("/orders")public class ordercontroller { // actions without any documentation or comments.}
7. 明智地使用查询参数
查询参数允许客户端对结果进行过滤、排序和分页,从而增强灵活性。
好示例:支持分页和过滤的端点。
@getmapping("/products")public responseentity<list> getproducts( @requestparam optional category, @requestparam(defaultvalue = "0") int page, @requestparam(defaultvalue = "10") int size) { list products = productservice.findproducts(category, page, size); return responseentity.ok(products);}
避免示例:返回大型数据集而不进行任何过滤或分页。
@getmapping("/products")public responseentity<list> getallproducts() { return responseentity.ok(productservice.findall()); // excessive data returned.}
8. 实施 http 缓存策略
缓存通过最小化服务器负载和响应时间来提高性能。
好示例:使用缓存控制标头来优化响应。
@getmapping("/products/{id}")public responseentity getproductbyid(@pathvariable long id) { product product = productservice.findbyid(id); return responseentity.ok() .cachecontrol(cachecontrol.maxage(30, timeunit.seconds)) .body(product);}
避免示例:未能利用缓存标头,导致冗余数据传输。
@getmapping("/products/{id}")public responseentity getproductbyid(@pathvariable long id) { return responseentity.ok(productservice.findbyid(id)); // no caching utilized.}
9. 确保直观的 api 设计
api 应该简单、自描述,并具有逻辑命名约定。
好示例:使用清晰且描述性的端点名称。
@postmapping("/users")public responseentity registeruser(@requestbody user user) { // clearly indicates user registration.}@getmapping("/users/{id}")public responseentity fetchuserbyid(@pathvariable long id) { // clearly indicates fetching a user by id.}
避免示例:令人困惑的端点路径掩盖了其目的。
@putmapping("/updateuserinfo")public responseentity updateuser(@requestbody user user) { // unclear path; doesn't specify the resource being updated.}
10.启用响应压缩
通过响应压缩优化有效负载大小可提高性能。
好示例:配置服务器以启用 gzip 压缩。
propertiescopy code# in spring boot application.propertiesserver.compression.enabled=trueserver.compression.mime-types=application/json,text/html
避免示例:发送大响应而不压缩,增加加载时间。
@getmapping("/products")public responseentity<list> getallproducts() { return responseentity.ok(productservice.findall()); // large payload without compression.}
11.拥抱异步处理
异步操作对于管理长时间运行的任务而不阻塞客户端至关重要。
很好示例:使用异步处理处理批量请求。
@postmapping("/orders/batch")public responseentity batchcreateorders(@requestbody list orders) { completablefuture future = orderservice.createordersasync(orders); httpheaders headers = new httpheaders(); headers.setlocation(uri.create("/orders/batch/status")); return responseentity.accepted().headers(headers).build();}
避免示例:同步处理使客户端等待长时间操作。
@PostMapping("/orders/batch")public ResponseEntity<List> batchCreateOrders(@RequestBody List orders) { List createdOrders = orderService.createOrders(orders); // This could block. return ResponseEntity.ok(createdOrders);}
结论
通过应用这些最佳实践,开发人员可以创建健壮、可维护且用户友好的 api。这种方法不仅有助于构建高质量的 api,还确保它们可以随着时间的推移而发展,而不会对客户造成干扰。
参考
restful web api 设计gitlab api 设计指南rest 架构约束标准响应状态代码api 风格指南学习 rest api 设计
以上就是Java API 设计的关键最佳实践的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/452466.html
微信扫一扫
支付宝扫一扫