Gone框架介绍24 - Gone vs Spring,写给想转 Go 的 Java程序员

Gone vs Spring,写给想转 Go 的 Java程序员

Gone是我们开发的 Golang 依赖注入框架,Spring是Java的依赖注入框架;为了便于Spring程序员转Golang快速上手Gone,我们在这里对他们的依赖注入做一下对比。

依赖模块导入

Spring

在项目管理工具中引入依赖;项目启动后自动扫描加载。
在 Maven 中 引入依赖

<dependency>
    <groupId>com.github.example</groupId>
    <artifactId>example</artifactId>
    <version>1.0.0</version>
</dependency>

在 Gradle 中 引入依赖

implementation 'com.github.example:example:1.0.0'

Gone

在MasterPriest函数中加载依赖模块提供的Priest函数;在启动前执行go mod tidy将依赖的包写入go.mod文件。

func MasterPriest(cemetery gone.Cemetery) error {
	_ = goner.XormPriest(cemetery) //加载xorm的依赖
	_ = goner.GinPriest(cemetery)  //加载gin的依赖

	_ = Priest(cemetery)
	return nil
}

func main() {
    gone.Run(MasterPriest)
}

注入依赖

Spring

在结构体属性上添加@Autowired注解,表示该属性是需要依赖注入的。

@Component
public class DemoController {

    @Autowired
    private IDemo demoSvc; //该属性是需要依赖注入的
}

Goner

在结构体属性上添加gone标签,表示该属性是需要依赖注入的,可以参考Gone支持哪些方式注入?

type demoController struct {
	gone.Flag
	demoSvc     service.IDemo `gone:"*"` //该属性是需要依赖注入的
}

配置注入

Spring

在结构体属性上添加@Value("${key}")注解,表示该属性是需要依赖注入的。

@Component
public class UseConfig {
    @Value("${my.conf.int}")
    private Integer int;
}


### Gone
在结构体属性上添加`gone:"config,${key},default=${defaultValue}"`标签,表示该属性是需要依赖注入的,可以参考[通过内置Goners支持配置文件](https://goner.fun/zh/guide/config.html)
```go
type UseConfig struct {
	gone.Flag

	int      int           `gone:"config,my.conf.int"`
	int8     int8          `gone:"config,my.conf.int8"`
	printInt *int          `gone:"config,my.conf.int8"` //指针 指向int
	float64  float64       `gone:"config,my.conf.float64"`
	string   string        `gone:"config,my.conf.string"`
	bool     bool          `gone:"config,my.conf.bool"`
	duration time.Duration `gone:"config,my.conf.duration"`
	defaultV string        `gone:"config,my.conf.default,default=ok"`

	sub *SubConf `gone:"config,my.conf.sub"` //指针,指向结构体

	subs []SubConf `gone:"config,my.conf.subs"` //数组
}

HTTP 参数注入

HTTP参数注入,就是自动读取HTTP请求的Query参数,并注入到Controller的方法中。

Gone支持多种HTTP参数注入,可以取到URL、Header、Body、Cookie、Form、Path等参数,
参考:HTTP 注入说明

注入Query参数

Spring
@RestController()
@RequestMapping("/demo")  //路由分组为/demo
public class CallbackController {

    @GetMapping("/hello") //GET方法,当前路由是/demo/hello
    public String hello(
            @RequestParam String name  //注入Query中的name参数
    ) {
        return "hello, " + name;
    }
}
Gone
type controller struct {
	gone.Flag
	rootRouter gone.RouteGroup `gone:"*"` //注入根路由
}

func (ctr *controller) Mount() gone.GinMountError {
	ctr.rootRouter.
		Group("/demo"). //路由分组为/demo

		//GET 方法
		GET(
			"/hello", // 当前路由是/demo/hello
			func(in struct {
				name string `gone:"http,query"` //注入Query中的name参数
			}) string {
				return "hello, " + in.name
			},
		)

	return nil
}

注入路径参数

Spring
@RestController()
@RequestMapping("/demo")  //路由分组为/demo
public class CallbackController {

    @GetMapping("/hell/{name}")//设置路径模式
    public String demo(
            @PathVariable(value = "name") String name //注入路径参数
    ) {
        return "hello, " + name;
    }
}
Gone
type controller struct {
	gone.Flag
	rootRouter gone.RouteGroup `gone:"*"` //注入根路由
}

func (ctr *controller) Mount() gone.GinMountError {
	ctr.rootRouter.
		Group("/demo"). //路由分组为/demo

		//GET 方法
		GET(
			"/hello/:name", //设置路径模式
			func(in struct {
				name string `gone:"http,param"` //注入路径参数
			}) string {
				return "hello, " + in.name
			},
		)

	return nil
}

请求体注入

Spring
@RestController()
@RequestMapping("/demo")  //路由分组为/demo
public class CallbackController {

    //订阅接收请求的POJO
    public static class Req {
        private String name;

        public String GetName() {
            return name;
        }

        public void SetName(String name) {
            this.name = name;
        }
    }

    @PostMapping("/hello")
    public String demo(
            @RequestBody Req req //注入请求体
    ) {
        return "hello, " + req.name;
    }
}
Gone
type controller struct {
	gone.Flag
	rootRouter gone.RouteGroup `gone:"*"` //注入根路由
}

func (ctr *controller) Mount() gone.GinMountError {
	type Req struct {
		Name string `json:"name"`
	}

	ctr.rootRouter.
		Group("/demo").
		POST(
			"/hello/:name", //注入请求体
			func(in struct {
				req Req `gone:"http,body"`
			}) string {
				return "hello, " + in.req.Name
			},
		)

	return nil
}

Gone支持多种HTTP参数注入,可以取到URL、Header、Body、Cookie、Form、Path等参数,
参考:HTTP 注入说明

总结

SpringGone在依赖模块导入、依赖注入、配置注入以及HTTP参数注入方面有不同的实现方式。

Spring通过项目管理工具(如Maven或Gradle)引入依赖,并自动扫描加载依赖模块。依赖注入使用@Autowired注解,配置注入使用@Value("${key}")注解,HTTP参数注入则通过@RequestParam@PathVariable@RequestBody注解实现。

相对而言,Gone在MasterPriest函数中手动加载依赖模块,通过gone标签进行依赖和配置注入,并支持多种HTTP参数注入方式(如URL、Header、Body、Cookie、Form、Path等),灵活处理HTTP请求参数。

求赞助

如果觉得还可以,请帮忙在github上点个 ⭐️吧:
github地址:https://github.com/gone-io/gone

福利🔥添加交流群,赠送 Golang 多套 学习资料,夯实基础👍🏻👍🏻

上一篇:Gone框架介绍23 - Gone对Xorm的一点点增强

  • 68
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
2006 - Server has gone away错误是指在MySQL长连接很久没有新的请求发起,达到了服务器端的timeout,导致服务器强行关闭连接。当再次通过这个连接发起查询时,就会报这个错误。这个错误通常在PHP脚本中出现。\[1\] 造成这个错误的原因可能有多种。一种可能是内存不足,这可能是应用程序服务器内存不足或者数据库服务器内存不足导致的。通过查看应用程序服务器的内存使用情况,如果可供应用程序使用的内存足够,那么可以排除应用程序服务器内存不足的可能性。而数据库服务器的内存使用情况无法直接查看,但如果出现性能问题,DBA通常会有反应,因此可以基本排除数据库服务器内存不足的可能性。\[3\] 另一个可能的原因是连接数太多。如果同时有大量的连接请求,服务器可能无法处理所有的连接,导致一些连接被关闭。这可能会导致一些查询报2006 - Server has gone away错误。\[3\] 为了解决这个问题,可以尝试以下几个方法: 1. 增加服务器端的timeout时间,以允许更长时间的连接空闲。 2. 检查应用程序服务器和数据库服务器的内存使用情况,确保内存足够。 3. 优化数据库查询,减少查询的时间和资源消耗。 4. 调整连接池的大小,以适应当前的连接需求。 5. 如果可能,考虑使用短连接而不是长连接,以避免连接空闲时间过长导致被关闭。 综上所述,2006 - Server has gone away错误通常是由于长连接空闲时间过长导致服务器关闭连接所致。可以通过增加timeout时间、优化查询和调整连接池大小等方法来解决这个问题。 #### 引用[.reference_title] - *1* [MySQL server has gone away 问题的解决方法](https://blog.csdn.net/swatyb/article/details/83552606)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [(2006,Mysql Server has gone away)问题处理](https://blog.csdn.net/xiaoyi52/article/details/107737189)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dapeng-大鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值