groovy 的常用操作
Posted 阿拉的梦想
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了groovy 的常用操作相关的知识,希望对你有一定的参考价值。
groovy 的常用操作
全局变量
方式1:static 定义的全局变量可以在不同的类使用
class Globals
//定义全局变量
static Integer NUM;
if(Globals.NUM == null)
//初始化
Globals.NUM = 1;
println "初始化";
//日志输出
println show();
//自定义方法,访问变量
Integer show()
return Globals.NUM;
方式2:使用@Field 定义的全局变量可以在不通的方法间共用
import groovy.transform.Field
//定义全局变量
@Field Integer NUM;
if(NUM == null)
//初始化
NUM = 1;
println '初始化';
//日志输出
println show();
//自定义方法,访问变量
Integer show()
return NUM;
JSON操作
字符串转json对象:
jsonSlpuer.parse()方法,可以从字符串、文件、byte[]、url、输入流等直接解析为对象。
def jsonSlpuer = new JsonSlurper()
def jsonObj=jsonSlpuer.parseText(str)
对象转json字符串:
package file
import groovy.json.JsonOutput
import objectorention.Person
def list = [new Person(name: 'John', age: 25),
new Person(name: 'Major', age: 26)]
println JsonOutput.toJson(list)
发送http
1.get 超简单
def res1 = new URL('http://www.baidu.com').text
// or
def res2 = 'http://www.baidu.com'.toURL().text
//设置超时时间 ms
def res3 = new URL('http://www.baidu.com').getText(readTimeout: 200000)
2. get 自带请求头
/**
* 发送httpGet请求,自带请求头
* @param url 必填
* @param headerMap 非必填
* @return
*/
static def httpGet(url, headerMap)
def conn = new URL(url).openConnection()
conn.setRequestMethod("GET")
if (headerMap)
headerMap.each header ->
conn.setRequestProperty(header.key, header.value)
return conn.content.text
3. post 传入header和body返回json
static void main(String[] args)
def url = "http://demo.com:8088/user/special/list/2/10"
def data = [:]
def isJson = true
def headerMap = [:]
headerMap.put("Content-Type", "application/json")
headerMap.put("Cookie", "MS_SESSION_ID=123456")
headerMap.put("CSRF-TOKEN", "12345")
def post = httpPostJson(url, data, headerMap, isJson)
println(post)
//工具方法
static def httpPostJson(url, body = null, headerMap, isJson = false)
def conn = new URL(url).openConnection()
conn.setRequestMethod("POST")
if(headerMap)
headerMap.eachheader->
conn.setRequestProperty(header.key, header.value)
if (body!=null)
// 写入body
conn.doOutput = true
def writer = new OutputStreamWriter(conn.outputStream)
writer.write(JsonOutput.toJson(body))
writer.flush()
writer.close()
if(isJson)
def json = new JsonSlurper()
def result = json.parseText(conn.content.text)
return result
else
return conn.content.text
SQL操作
sql查询、新增、更新
//数据库连接
def sql = Sql.newInstance('jdbc:mysql://10.0.0.1:3306/demo?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false', 'root', '123456', 'com.mysql.jdbc.Driver')
def saveSumary(String fullName, BigDecimal cost, def sql)
cost.setScale(2, BigDecimal.ROUND_HALF_UP)
def percent='10%'
def row = sql.firstRow('select * from apportion_summary where full_name=?', [fullName])
if (row == null)
def insertSql = "insert into apportion_summary(full_name,`final_cost_" + percent + "`) values(?,?)"
try
sql.executeInsert(insertSql, [fullName, cost])
catch (Exception e)
log.error("保存数据到Mysql异常,fullName=,cost=", fullName, cost)
throw new Exception()
else
def updateSql = "update apportion_summary set `final_cost_" + percent + "`=? where full_name=?"
sql.executeUpdate(updateSql, [cost, fullName])
sql.close()
查询并新建字段
/**
* 新建字段
* @return
*/
def createColumn(def sql)
//def sql = Sql.newInstance('jdbc:mysql://10.0.0.1:3306/demo?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false','root', '123456', 'com.mysql.jdbc.Driver')
//def execute = sql.execute("desc apportion_summary ")
def columns = []
sql.eachRow("desc apportion_summary", it -> columns.add(it[0]) )
if (!columns.contains("final_cost_" + percent))
def str = "ALTER TABLE demo.apportion_summary ADD `final_cost_" + percent + "` DECIMAL(10,2) comment '去掉调用占比" + percent + "后的'"
sql.execute(str)
//sql.close()
批量新增
def saveMembers(List<Member> members)
def conn = Sql.newInstance('jdbc:mysql://10.0.0.1:3306/demo?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false', 'root', '123456', 'com.mysql.jdbc.Driver')
conn.withTransaction
def updateCounts = conn.withBatch stmt ->
for(member in members)
stmt.addBatch("INSERT INTO `member` (member_name, pinyin, member_key, member_type, dept_code, full_dept_name, full_dept_code) VALUES( '"+member.memberName+"', '"+member.pinyin+"', '"+member.memberKey+"', "+member.memberType+", '"+member.deptCode+"', '"+member.fullDeptName+"', '"+member.fullDeptCode+"')")
println("新增数据="+updateCounts.size())
conn.close()
列表查询
def getAllMembers()
def conn = Sql.newInstance('jdbc:mysql://10.0.0.1:3306/demo?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false', 'root', '123456', 'com.mysql.jdbc.Driver')
def map=[:]
conn.eachRow('select * from member') row ->
def member = new Member()
member.memberName=row.member_name
member.pinyin=row.pinyin
member.memberKey=row.member_key
member.memberType=row.member_type
member.deptCode=row.dept_code
member.fullDeptName=row.full_dept_name
member.fullDeptCode=row.full_dept_code
map.put(member.memberKey,member)
conn.close()
return map
以上是关于groovy 的常用操作的主要内容,如果未能解决你的问题,请参考以下文章