路由
介绍
这里路由的概念对应浏览器中的 URL,表示一个唯一的访问地址。 路由是一个对外提供访问业务方法的地址,在类和方法上添加了路由的,也称为 Action。
路由注解
业务框架中提供了两个注解,分别是
- @ActionController 主路由 (作用在业务类上)
- @ActionMethod 子路由(作用在业务方法上)
@ActionController(2)
public class DemoAction {
@ActionMethod(0)
public HelloMessage here(HelloMessage message) {
message.name = message.name + ", I'm here ";
return message;
}
@ActionMethod(1)
public HelloMessage say(HelloMessage message) {
message.name = message.name + ", I'm say ";
return message;
}
}
上面代码中定义了两个对外开放的 action
- here 是一个 action,设定的主路由值为 2,子路由值为 0。
- say 是一个 action,设定的主路由值为 2,子路由值为 1。
可以发现 DemoAction 类下的方法(Action)都会使用 DemoAction 对应的主路由 “2”, 方法则用自己的 ActionMethod 值为子路由。
如何理解路由
- @ActionController 可以理解为 Spring框架中的 @RestController 注解 (作用在类上的)
- @ActionMethod 可以理解为 Spring框架中的 @GetMapping 注解 (作用在方法上的)
举例说明
URL: https://ip:port/user/hello
当在浏览器输入上面的 URL 后, 表示访问 user 模块下的 hello 方法。
user 对应业务框架中的主路由 @ActionController
hello 对应业务框架中的子路由 @ActionMethod
最佳实践
在开发时,我们可以将路由定义为常量。
一个游戏通常由多个模块组成,每个模块下会有多个业务方法,我们可以将所有模块的主路由定义到一个接口中。
每个模块单独一个文件,而每个模块文件管理对应的业务方法。 模块文件命名以 xxxCmd 结尾,单独模块下主路由统一命名为 cmd。
public interface CmdModule {
int heroCmd = 1;
int equipCmd = 2;
}
/** 英雄模块 */
public interface HeroCmd {
int cmd = CmdModule.heroCmd;
int hello = 0;
int age = 1;
}
/** 装备模块 */
public interface EquipCmd {
int cmd = CmdModule.equipCmd;
/** subCmd : 强化装备 */
int intensify = 0;
/** subCmd : 升级 */
int upgrade = 1;
}
@ActionController(HeroCmd.cmd)
public final class HeroAction {
@ActionMethod(HeroCmd.hello)
public String helo(String message) {
return message + ", Michael Jackson";
}
}
之所以推荐定义路由常量是为了好区分功能模块。比如:
- 玩家模块:与玩家模块相关的方法(经验增加、玩家升级)
- 装备模块:与装备模块相关的方法(装备强化、装备镶嵌宝石、装备鉴定等)
这里的建议是,一个功能模块定义一个 cmd,功能模块下的一个方法定义一个 subCmd。
路由计算工具
tip
游戏前端的同学,可以 copy 这段代码,用于计算路由。如果使用了 ioGame SDK,则可以忽略。
@UtilityClass
public class CmdKit {
public int getCmd(int cmdMerge) {
return cmdMerge >> 16;
}
public int getSubCmd(int cmdMerge) {
return cmdMerge & 0xFFFF;
}
public int merge(int cmd, int subCmd) {
return (cmd << 16) + subCmd;
}
}