当前我们正处在 AI 时代,但是在基础架构领域,仍然处在云原生时代。云原生仍然是当前时代的风口之一。作为一个 Go 开发者,职业进阶的下一站就是学习云原生技术。作为 Go 开发者学习云原生技术有得天独厚的优势,这是因为 Go 天生适合云原生。本文就来介绍下为什么 Go 天生适合云原生。
易学易用
Go 相比其他语言语法关键字更少,上手难度更低,学习曲线更平缓。Go 只有 25 个保留关键字:
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
这让初学者能更多地关注如何写出优雅的代码,而不是陷于各种语法糖或“炫技”写法。
Go 设计之初即为弥补 C++ 的臃肿与低效,强调短编译时间、高运行效率、强健稳定性和完善的编译时检查,并提供覆盖整个软件生命周期的官方工具链。
并发编程的优势
下面分别看一下 Python、Java、C++ 的简单并发示例:
Python:
import threading, time
def thread_function(name):
print(f"Thread {name} started")
time.sleep(2)
print(f"Thread {name} ended")
thread1 = threading.Thread(target=thread_function, args=(1,))
thread2 = threading.Thread(target=thread_function, args=(2,))
thread1.start(); thread2.start()
thread1.join(); thread2.join()
print("Main thread ended")
Java:
static class MyThread extends Thread {
int id;
MyThread(int id){ this.id = id; }
public void run(){
System.out.println("Thread " + id + " started");
Thread.sleep(2000);
System.out.println("Thread " + id + " ended");
}
}
public static void main(String[] args) {
MyThread t1 = new MyThread(1), t2 = new MyThread(2);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("Main thread ended");
}
C++:
void thread_function(int id){
std::cout << "Thread " << id << " started\n";
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Thread " << id << " ended\n";
}
int main(){
std::thread t1(thread_function,1), t2(thread_function,2);
t1.join(); t2.join();
std::cout << "Main thread ended\n";
}
相比之下,其他语言的并发写法更冗长,也更容易出错。Go 只需 go
关键字启动一个协程,用 chan
在协程间传递信号,既简单又直观,出错率自然也更低。
示例:用 context.Done()
控制多协程退出
func watch(ctx context.Context, event chan string) {
for {
select {
case <-ctx.Done():
return
case msg := <-event:
// 处理 msg
}
}
}
定时任务也同样优雅:
func watch(ctx context.Context) {
ticker := time.NewTicker(10 * time.Second)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
// 定期处理
}
}
}
在云原生场景下,微服务之间往往需要并行地拉取多个下游服务的数据,串行调用难以支撑高性能,因此高效并发对响应速度至关重要。
专注可维护性
当成千上万的开发者在数千万行代码的大型代码库上持续工作多年时,真正痛苦的问题便会显现。随着程序体量的增长,编译时间会逐渐增加,从而影响开发速度。因此,快速构建成为 Go 的一大优势。
由多人维护的代码库会混杂各种编程风格。在代码库的生命周期中,代码不断被打补丁,最终问题层出不穷。技术债务积累,频繁的变更会导致文档滞后,甚至不完整。Go 在这方面也做了不少努力。例如,针对 if-else 语句,Go 只允许一种书写风格,避免程序员为是否换行争论不休。
此外,Go 提供了格式化工具(如 gofmt),让不同人写出的代码保持一致风格,开发者只需专注于业务逻辑。
Kubernetes 的强大力量
云原生最重要的容器编排工具 Kubernetes 就是用 Go 编写的。想要玩转云原生,就绕不开 Go;更多 Go 开发者也持续为其生态贡献工具链。
例如微服务框架 go-zero,让初始化服务、注册发现、熔断、链路追踪等功能极其简单,大大降低了使用 Go 开发云原生应用的门槛。
微服务的广泛应用
随着互联网用户激增,架构从单体到分布式微服务已成趋势。各服务之间通过 API 交互,下游对实现语言并不关心,这正为 Go 的普及提供了沃土。
已运行的稳定服务无需重写,新功能只需在微服务中新建 API 即可。Go 以轻量、高性能和易部署的优势,在微服务浪潮中快速获得一席之地。
虽然 Java 在企业领域依然占据主导,Python 在数据科学领域不可替代,但针对大规模并发和多团队协作,Go 的静态类型、简单语法与高效并发都让它在云原生时代大放异彩。