Groovy脚本案例

wen java案例 2

本文目录导读:

Groovy脚本案例

  1. 文件处理脚本
  2. JSON处理脚本
  3. 数据库操作脚本
  4. Web请求脚本
  5. Excel文件处理
  6. 日志分析脚本
  7. 自动化测试脚本
  8. 系统监控脚本
  9. 注意事项:

我来提供几个实用的Groovy脚本案例,涵盖不同场景:

文件处理脚本

// 文件批量重命名脚本
import java.nio.file.*
def directory = new File("/path/to/files")
def prefix = "2024_"
directory.eachFile { file ->
    if (file.isFile() && file.name.endsWith('.txt')) {
        def newName = prefix + file.name
        def newFile = new File(directory, newName)
        file.renameTo(newFile)
        println "Renamed: ${file.name} -> ${newName}"
    }
}
搜索替换
def sourceFile = new File("config.txt")
def content = sourceFile.text
content = content.replaceAll("oldValue", "newValue")
sourceFile.text = content

JSON处理脚本

@Grab('groovy-json')
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
// 解析JSON
def jsonText = '''
{
    "users": [
        {"name": "Alice", "age": 30},
        {"name": "Bob", "age": 25}
    ]
}
'''
def jsonSlurper = new JsonSlurper()
def data = jsonSlurper.parseText(jsonText)
data.users.each { user ->
    println "用户: ${user.name}, 年龄: ${user.age}"
}
// 创建JSON
def result = [
    status: "success",
    timestamp: new Date().time,
    users: data.users.findAll { it.age >= 25 }
]
println JsonOutput.prettyPrint(JsonOutput.toJson(result))

数据库操作脚本

@Grab('mysql:mysql-connector-java:8.0.33')
@GrabConfig(systemClassLoader = true)
import groovy.sql.Sql
// 连接数据库
def db = Sql.newInstance(
    "jdbc:mysql://localhost:3306/mydb",
    "username",
    "password",
    "com.mysql.cj.jdbc.Driver"
)
// 查询数据
db.eachRow("SELECT * FROM users WHERE age > ?", [25]) { row ->
    println "用户: ${row.name}, 邮箱: ${row.email}"
}
// 插入数据
db.execute("INSERT INTO users (name, age, email) VALUES (?, ?, ?)", 
    ["Charlie", 28, "charlie@example.com"])
// 更新数据
db.executeUpdate("UPDATE users SET age = ? WHERE name = ?", [31, "Charlie"])
// 批量操作
db.withTransaction {
    db.withBatch(10) { stmt ->
        (1..100).each { i ->
            stmt.addBatch("INSERT INTO logs (message) VALUES ('Log $i')")
        }
    }
}
db.close()

Web请求脚本

// HTTP请求处理
def url = new URL("https://api.github.com/users/octocat/repos")
def connection = url.openConnection()
connection.requestMethod = "GET"
connection.setRequestProperty("Accept", "application/vnd.github.v3+json")
if (connection.responseCode == 200) {
    def response = connection.inputStream.text
    def repos = new groovy.json.JsonSlurper().parseText(response)
    repos.each { repo ->
        println "仓库: ${repo.name} - 描述: ${repo.description}"
    }
} else {
    println "请求失败: ${connection.responseCode}"
}
// POST请求
def postData = [title: "测试", content: "内容"]
def encodedData = postData.collect { k, v -> "${k}=${URLEncoder.encode(v.toString(), 'UTF-8')}" }.join('&')
def postConn = new URL("https://httpbin.org/post").openConnection()
postConn.requestMethod = "POST"
postConn.doOutput = true
postConn.outputStream.write(encodedData.getBytes("UTF-8"))
postConn.outputStream.flush()
println "POST响应状态: ${postConn.responseCode}"

Excel文件处理

@Grab('org.apache.poi:poi:5.2.3')
@Grab('org.apache.poi:poi-ooxml:5.2.3')
import org.apache.poi.ss.usermodel.*
import org.apache.poi.xssf.usermodel.XSSFWorkbook
// 写入Excel
def workbook = new XSSFWorkbook()
def sheet = workbook.createSheet("员工数据")
def headers = ["姓名", "部门", "薪资", "入职日期"]
def headerRow = sheet.createRow(0)
headers.eachWithIndex { header, index ->
    headerRow.createCell(index).setCellValue(header)
}
// 示例数据
def employees = [
    ["张三", "技术部", 12000, "2023-01-15"],
    ["李四", "市场部", 10000, "2023-03-20"],
    ["王五", "财务部", 11000, "2023-06-01"]
]
employees.eachWithIndex { emp, rowIndex ->
    def row = sheet.createRow(rowIndex + 1)
    emp.eachWithIndex { value, colIndex ->
        row.createCell(colIndex).setCellValue(value.toString())
    }
}
// 保存文件
def output = new FileOutputStream("employees.xlsx")
workbook.write(output)
output.close()
workbook.close()
println "Excel文件已生成!"
// 读取Excel
def input = new FileInputStream("employees.xlsx")
def readWorkbook = new XSSFWorkbook(input)
def readSheet = readWorkbook.getSheetAt(0)
readSheet.each { row ->
    def values = []
    row.each { cell ->
        values << cell.toString()
    }
    println "行数据: ${values.join(', ')}"
}
readWorkbook.close()

日志分析脚本

// 分析Nginx访问日志
def logFile = new File("/var/log/nginx/access.log")
def ipCount = [:]
logFile.eachLine { line ->
    // 简单解析:获取IP地址
    def matcher = line =~ /^(\d+\.\d+\.\d+\.\d+)/
    if (matcher.find()) {
        def ip = matcher[0][1]
        ipCount[ip] = (ipCount[ip] ?: 0) + 1
    }
}
// 按访问次数排序
def sorted = ipCount.sort { -it.value }
println "最频繁的IP地址:"
sorted.take(10).each { ip, count ->
    println "$ip - $count 次访问"
}
// 统计404错误
def errorCount = 0
logFile.eachLine { line ->
    if (line.contains('" 404 ')) {
        errorCount++
    }
}
println "404错误总数: $errorCount"

自动化测试脚本

// 简单的接口测试脚本
class APITester {
    def baseUrl
    def testPassed = 0
    def testFailed = 0
    def testGet(String path, Map expectedParams) {
        def url = "${baseUrl}${path}"
        def restClient = new groovyx.net.http.RESTClient(url)
        try {
            def response = restClient.get(query: expectedParams)
            if (response.status == 200) {
                testPassed++
                println "✅ GET $path - 成功"
            } else {
                testFailed++
                println "❌ GET $path - 返回${response.status}"
            }
        } catch (Exception e) {
            testFailed++
            println "❌ GET $path - 异常: ${e.message}"
        }
    }
    def testPost(String path, Map data) {
        def restClient = new groovyx.net.http.RESTClient("${baseUrl}${path}")
        try {
            def response = restClient.post(body: data, requestContentType: 'application/json')
            if (response.status == 201) {
                testPassed++
                println "✅ POST $path - 成功"
            } else {
                testFailed++
                println "❌ POST $path - 返回${response.status}"
            }
        } catch (Exception e) {
            testFailed++
            println "❌ POST $path - 异常: ${e.message}"
        }
    }
    def summary() {
        println "\n测试汇总:"
        println "通过: $testPassed"
        println "失败: $testFailed"
        println "总用例: ${testPassed + testFailed}"
    }
}
// 使用示例
def tester = new APITester(baseUrl: "https://jsonplaceholder.typicode.com")
tester.testGet("/posts/1", [id: 1])
tester.testGet("/users", [limit: 5])
tester.testPost("/posts", [title: "测试", body: "内容", userId: 1])
tester.summary()

系统监控脚本

// 系统资源监控
import java.lang.management.*
def runtime = Runtime.getRuntime()
println "=== 系统监控报告 (${new Date()}) ==="
// 内存信息
def totalMem = runtime.totalMemory() / (1024 * 1024)
def freeMem = runtime.freeMemory() / (1024 * 1024)
def usedMem = totalMem - freeMem
println "内存使用: ${usedMem.round(2)} MB / ${totalMem.round(2)} MB"
// CPU信息
def osMxBean = ManagementFactory.getOperatingSystemMXBean()
println "CPU核心数: ${osMxBean.availableProcessors}"
println "系统负载: ${osMxBean.systemLoadAverage}"
// 线程信息
def threadMxBean = ManagementFactory.getThreadMXBean()
println "活动线程数: ${threadMxBean.threadCount}"
println "峰值线程数: ${threadMxBean.peakThreadCount}"
// 磁盘空间
def root = new File("/")
def freeSpace = root.freeSpace / (1024 * 1024 * 1024)
def totalSpace = root.totalSpace / (1024 * 1024 * 1024)
println "磁盘使用: ${totalSpace - freeSpace} GB / ${totalSpace} GB"

注意事项:

  1. 依赖管理:使用@Grab注解自动下载依赖
  2. 错误处理:始终包含适当的异常处理
  3. 资源管理:记得关闭文件流、数据库连接等资源
  4. 性能优化:大数据量时考虑使用流式处理
  5. 安全性:不要在脚本中硬编码敏感信息

这些案例覆盖了常见的开发场景,你可以根据实际需求调整和组合这些脚本。

抱歉,评论功能暂时关闭!