Oracle-Sentry/docs/cn/script/groovy/入门.md

56 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## Groovy 脚本编写
### 基本格式
Groovy 语言的脚本基本格式如下:
```groovy
info {
// 脚本信息, 遵循 Java 的 GAV 规则.
// 脚本英文名
artifact 'demo'
// 所属组(如果有域名, 就是自己的域名的倒序, 例如 tieba.baidu.com 就是 com.baidu.tieba)
// 如果没有, 也可以用 github 的.
group 'org.example'
// 脚本版本号.
version '0.0.1'
}
// 注册触发器.
// 目前触发器有两种选择
// once 单次触发器: 只会运行一次.
// timer 定时器触发器: 根据设定的 cron 表达式定时运行.
trigger("once") {
// once 触发器没有参数.
// 运行代码块, 要执行的东西都在这个代码块里.
run {
// 在这里做些什么, 比如
println "From script."
}
}
// 在外面可以定义一些全局变量.
def formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
// 这里注册定时器触发器.
trigger("timer") {
// time 参数指定 Cron 表达式, 像这样设置表达式字符串后就可以了.
// 比如这里设定一分钟执行一次.
time "0 0/1 * * * ? "
run {
// 在这里做些什么, 比如
println "当前时间: ${formatter.format(LocalDateTime.now())}"
}
}
```
Groovy 语言比较贴近 Java实际开发与 Java 没什么区别(相比于 Java 多了不少语法糖,但还是兼容 Java 的)。
## 我能在脚本中使用什么?
目前你能使用的东西有:
- `HTTP`:一个 HttpClient允许你访问 Http 资源。
- `InstanceManager`:计算实例(就是服务器)管理器,可以获取所有的服务器实例,通过实例对象能获取和操作服务器。
除此之外,还有 Java 基本库与 Groovy 基本库可供脚本使用。