go语言注入容器,go 模块引用-成都快上网建站

go语言注入容器,go 模块引用

Go语言的应用

Go语言由Google公司开发,并于2009年开源,相比Java/Python/C等语言,Go尤其擅长并发编程,性能堪比C语言,开发效率肩比Python,被誉为“21世纪的C语言”。

创新互联公司是一家以网络技术公司,为中小企业提供网站维护、网站建设、网站制作、网站备案、服务器租用、域名注册、软件开发、小程序制作等企业互联网相关业务,是一家有着丰富的互联网运营推广经验的科技公司,有着多年的网站建站经验,致力于帮助中小企业在互联网让打出自已的品牌和口碑,让企业在互联网上打开一个面向全国乃至全球的业务窗口:建站服务热线:18980820575

Go语言在云计算、大数据、微服务、高并发领域应用应用非常广泛。BAT大厂正在把Go作为新项目开发的首选语言。

Go语言应用范围:

1、服务端开发:以前你使用C或者C++做的那些事情,用Go来做很合适,例如日志处理、文件系统、监控系统等;

2、DevOps:运维生态中的Docker、K8s、prometheus、grafana、open-falcon等都是使用Go语言开发;

3、网络编程:大量优秀的Web框架如Echo、Gin、Iris、beego等,而且Go内置的 net/http包十分的优秀;

4、Paas云平台领域:Kubernetes和Docker Swarm等;

5、分布式存储领域:etcd、Groupcache、TiDB、Cockroachdb、Influxdb等;

6、区块链领域:区块链里面有两个明星项目以太坊和fabric都使用Go语言;

7、容器虚拟化:大名鼎鼎的Docker就是使用Go语言实现的;

8、爬虫及大数据:Go语言天生支持并发,所以十分适合编写分布式爬虫及大数据处理。

go依赖注入dig包使用-来自uber公司

原文链接:

github:

Dependency Injection is the idea that your components (usually structs in go) should receive their dependencies when being created. This runs counter to the associated anti-pattern of components building their own dependencies during initialization. Let’s look at an example.

Suppose you have a Server struct that requires a Config struct to implement its behavior. One way to do this would be for the Server to build its own Config during initialization.

This seems convenient. Our caller doesn’t have to be aware that our Server even needs access to Config . This is all hidden from the user of our function.

However, there are some disadvantages. First of all, if we want to change the way our Config is built, we’ll have to change all the places that call the building code. Suppose, for example, our buildMyConfigSomehow function now needs an argument. Every call site would need access to that argument and would need to pass it into the building function.

Also, it gets really tricky to mock the behavior of our Config . We’ll somehow have to reach inside of our New function to monkey with the creation of Config .

Here’s the DI way to do it:

Now the creation of our Server is decoupled from the creation of the Config . We can use whatever logic we want to create the Config and then pass the resulting data to our New function.

Furthermore, if Config is an interface, this gives us an easy route to mocking. We can pass anything we want into New as long as it implements our interface. This makes testing our Server with mock implementations of Config simple.

The main downside is that it’s a pain to have to manually create the Config before we can create the Server . We’ve created a dependency graph here – we must create our Config first because of Server depends on it. In real applications these dependency graphs can become very large and this leads to complicated logic for building all of the components your application needs to do its job.

This is where DI frameworks can help. A DI framework generally provides two pieces of functionality:

A DI framework generally builds a graph based on the “providers” you tell it about and determines how to build your objects. This is very hard to understand in the abstract, so let’s walk through a moderately-sized example.

We’re going to be reviewing the code for an HTTP server that delivers a JSON response when a client makes a GET request to /people . We’ll review the code piece by piece. For simplicity sake, it all lives in the same package ( main ). Please don’t do this in real Go applications. Full code for this example can be found here .

First, let’s look at our Person struct. It has no behavior save for some JSON tags.

A Person has an Id , Name and Age . That’s it.

Next let’s look at our Config . Similar to Person , it has no dependencies. Unlike Person , we will provide a constructor.

Enabled tells us if our application should return real data. DatabasePath tells us where our database lives (we’re using sqlite). Port tells us the port on which we’ll be running our server.

Here’s the function we’ll use to open our database connection. It relies on our Config and returns a *sql.DB .

Next we’ll look at our PersonRepository . This struct will be responsible for fetching people from our database and deserializing those database results into proper Person structs.

PersonRepository requires a database connection to be built. It exposes a single function called FindAll that uses our database connection to return a list of Person structs representing the data in our database.

To provide a layer between our HTTP server and the PersonRepository , we’ll create a PersonService .

Our PersonService relies on both the Config and the PersonRepository . It exposes a function called FindAll that conditionally calls the PersonRepository if the application is enabled.

Finally, we’ve got our Server . This is responsible for running an HTTP server and delegating the appropriate requests to our PersonService .

The Server is dependent on the PersonService and the Config .

Ok, we know all the components of our system. Now how the hell do we actually initialize them and start our system?

First, let’s write our main() function the old fashioned way.

First, we create our Config . Then, using the Config , we create our database connection. From there we can create our PersonRepository which allows us to create our PersonService . Finally, we can use this to create our Server and run it.

Phew, that was complicated. Worse, as our application becomes more complicated, our main will continue to grow in complexity. Every time we add a new dependency to any of our components, we’ll have to reflect that dependency with ordering and logic in the main function to build that component.

As you might have guessed, a Dependency Injection framework can help us solve this problem. Let’s examine how.

The term “container” is often used in DI frameworks to describe the thing into which you add “providers” and out of which you ask for fully-build objects. The dig library gives us the Provide function for adding providers and the Invoke function for retrieving fully-built objects out of the container.

First, we build a new container.

Now we can add new providers. To do so, we call the Provide function on the container. It takes a single argument: a function. This function can have any number of arguments (representing the dependencies of the component to be created) and one or two return values (representing the component that the function provides and optionally an error).

The above code says “I provide a Config type to the container. In order to build it, I don’t need anything else.” Now that we’ve shown the container how to build a Config type, we can use this to build other types.

This code says “I provide a *sql.DB type to the container. In order to build it, I need a Config . I may also optionally return an error.”

In both of these cases, we’re being more verbose than necessary. Because we already have NewConfig and ConnectDatabase functions defined, we can use them directly as providers for the container.

Now, we can ask the container to give us a fully-built component for any of the types we’ve provided. We do so using the Invoke function. The Invoke function takes a single argument – a function with any number of arguments. The arguments to the function are the types we’d like the container to build for us.

The container does some really smart stuff. Here’s what happens:

That’s a lot of work the container is doing for us. In fact, it’s doing even more. The container is smart enough to build one, and only one, instance of each type provided. That means we’ll never accidentally create a second database connection if we’re using it in multiple places (say multiple repositories).

Now that we know how the dig container works, let’s use it to build a better main.

The only thing we haven’t seen before here is the error return value from Invoke . If any provider used by Invoke returns an error, our call to Invoke will halt and that error will be returned.

Even though this example is small, it should be easy to see some of the benefits of this approach over our “standard” main. These benefits become even more obvious as our application grows larger.

One of the most important benefits is the decoupling of the creation of our components from the creation of their dependencies. Say, for example, that our PersonRepository now needs access to the Config . All we have to do is change our NewPersonRepository constructor to include the Config as an argument. Nothing else in our code changes.

Other large benefits are lack of global state, lack of calls to init (dependencies are created lazily when needed and only created once, obviating the need for error-prone init setup) and ease of testing for individual components. Imagine creating your container in your tests and asking for a fully-build object to test. Or, create an object with mock implementations of all dependencies. All of these are much easier with the DI approach.

I believe Dependency Injection helps build more robust and testable applications. This is especially true as these applications grow in size. Go is well suited to building large applications and has a great DI tool in dig . I believe the Go community should embrace DI and use it in far more applications.

golang反射框架Fx

Fx是一个golang版本的依赖注入框架,它使得golang通过可重用、可组合的模块化来构建golang应用程序变得非常容易,可直接在项目中添加以下内容即可体验Fx效果。

Fx是通过使用依赖注入的方式替换了全局通过手动方式来连接不同函数调用的复杂度,也不同于其他的依赖注入方式,Fx能够像普通golang函数去使用,而不需要通过使用struct标签或内嵌特定类型。这样使得Fx能够在很多go的包中很好的使用。

接下来会提供一些Fx的简单demo,并说明其中的一些定义。

1、一般步骤

大致的使用步骤就如下。下面会给出一些完整的demo

2、简单demo

将io.reader与具体实现类关联起来

输出:

3、使用struct参数

前面的使用方式一旦需要进行注入的类型过多,可以通过struct参数方式来解决

输出

如果通过Provide提供构造函数是生成相同类型会有什么问题?换句话也就是相同类型拥有多个值呢?

下面两种方式就是来解决这样的问题。

4、使用struct参数+Name标签

在Fx未使用Name或Group标签时不允许存在多个相同类型的构造函数,一旦存在会触发panic。

输出

上面通过Name标签即可完成在Fx容器注入相同类型

5、使用struct参数+Group标签

使用group标签同样也能完成上面的功能

输出

基本上Fx简单应用在上面的例子也做了简单讲解

1、Annotated(位于annotated.go文件) 主要用于采用annotated的方式,提供Provide注入类型

源码中Name和Group两个字段与前面提到的Name标签和Group标签是一样的,只能选其一使用

2、App(位于app.go文件) 提供注入对象具体的容器、LiftCycle、容器的启动及停止、类型变量及实现类注入和两者映射等操作

至于Provide和Populate的源码相对比较简单易懂在这里不在描述

具体源码

3、Extract(位于extract.go文件)

主要用于在application启动初始化过程通过依赖注入的方式将容器中的变量值来填充给定的struct,其中target必须是指向struct的指针,并且只能填充可导出的字段(golang只能通过反射修改可导出并且可寻址的字段),Extract将被Populate代替。 具体源码

4、其他

诸如Populate是用来替换Extract的,而LiftCycle和inout.go涉及内容比较多后续会单独提供专属文件说明。

在Fx中提供的构造函数都是惰性调用,可以通过invocations在application启动来完成一些必要的初始化工作:fx.Invoke(function); 通过也可以按需自定义实现LiftCycle的Hook对应的OnStart和OnStop用来完成手动启动容器和关闭,来满足一些自己实际的业务需求。

Fx框架源码解析

主要包括app.go、lifecycle.go、annotated.go、populate.go、inout.go、shutdown.go、extract.go(可以忽略,了解populate.go)以及辅助的internal中的fxlog、fxreflect、lifecycle

gorilla/websocket使用教程

最近打算为我的网站添加一个服务器资源监视功能,需要服务端主动向前端推动资源占用数据。这时Http则不能达到要求。所以自然想到采用websocket。以前使用SpringBoot时使用websocket很简单,只需要将ServerEndpointExporter注入到bean容器并配合相应注解即可创建一个websocket服务。这里要感谢各位前辈的封装让我们能尽快实现相应的功能,但本次出于学习目并不是公司项目(效率稳定性至上)同时使用的开发语言为Golang,其web开发生态也不会像Java那样丰富,最后选择了开源实现 gorilla/websocket 项目地址

执行 go get github.com/gorilla/websocket 添加依赖

我们知道websocket由http升级而来,首先会发送附带Upgrade请求头的Http请求,所以我们需要在处理Http请求时拦截请求并判断其是否为websocket升级请求,如果是则调用 gorilla/websocket 库相应函数处理升级请求。

首相要创建Upgrader实例,该实例用于升级请求

其中 CheckOringin 是一个函数,该函数用于拦截或放行跨域请求。函数返回值为 bool 类型,即 true 放行, false 拦截。如果请求不是跨域请求可以不赋值,我这里是跨域请求并且为了方便直接返回 true

此时已经成功升级为websocket连接并获得一个conn实例,之后的发送接收操作皆有conn完成其类型为websocket.Conn。

首先向客户端发送消息使用 WriteMessage(messageType int, data []byte) ,参数1为消息类型,参数2消息内容

示例:

接受客户端消息使用 ReadMessage() 该操作会阻塞线程所以建议运行在其他协程上。该函数有三个返回值分别是,接收消息类型、接收消息内容、发生的错误当然正常执行时错误为 nil。一旦连接关闭返回值类型为-1可用来终止读操作。

示例:

同时可以为连接设置关闭连接监听,函数为 SetCloseHandler(h func(code int, text string) error) 函数接收一个函数为参数,参数为nil时有一个默认实现,其源码为:

可以看到作为参数的函数的参数为int和string类型正好和前端的close(long string)对应即前端调用close(long string)关闭连接后两个参数会被发送给后端并最终被 func(code int, text string) error 所使用。

示例:

则断开连接时将打印code和text

注意:要想使断连处理生效必须要有 ReadMessage() 操作否则不会触发断连处理操作。

以上是常用基础操作点击 官方API手册 学习更多。

最后:大幻梦森罗万象狂气断罪眼\ (••) /


文章标题:go语言注入容器,go 模块引用
网站路径:http://kswjz.com/article/dsgdooj.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流