在java开发的过程中,我们经常遇到一些需要对某个方法做切面的需求,通常做法是使用spring提供的aop功能,对方法做切面,例如方法出入参打印,接口mock等等。但很多时候,需要切面的方法是非spring容器管理的类,例如需要对okhttp、apachehttpclient请求做mock,判断http请求的参数、url为某个值时,返回测试结果,例如请求参数中包含username=tester,返回code=200。这种使用可以使用java agent,通过java agent修改类的字节码,实现对非spring容器管理对象的aop处理。但是使用javaagent后,启动时需要添加参数-javaagent:xxx.jar,使用方还需要下载对象的jar到本地,使用起来略显麻烦。proxy-sdk就是为了解决这个问题,通过maven、gradle依赖工具直接引入jar依赖即可,然后添加你的切面逻辑,springboot服务启动即可生效。
github - yingxinguo95/proxy-agent: java agent with springboot
按照github上的readme的指引我们引入jar包,从maven的中央仓库下载依赖。
<dependency> <groupid>io.github.yingxinguo95</groupid> <artifactid>proxy-sdk</artifactid> <version>0.0.1</version> <!-- 0.0.1拉取不到可以试试0.0.1-release --> <!--<version>0.0.1-release</version>--> </dependency>
配置需要代理方法配置和定义我们自己的需要重写逻辑,例如我们需要apache httpclient的请求方法,实现接口mock,判断当请求某个地址时返回测试数据,而不是真的请求对方。
例如以下代码,前置重写httpclient的execute方法,当请求baidu.com时就返回测试的json数据{\"code\":\"200\", \"msg\":\"mock data\"}
import io.github.proxy.annotation.proxyrecodecfg; import io.github.proxy.annotation.recodetype; import io.github.proxy.service.proxyrecode; import lombok.sneakythrows; import org.apache.http.*; import org.apache.http.client.methods.closeablehttpresponse; import org.apache.http.client.methods.httpentityenclosingrequestbase; import org.apache.http.client.methods.httpurirequest; import org.apache.http.entity.basichttpentity; import org.apache.http.message.basichttpresponse; import org.apache.http.message.basicstatusline; import org.apache.http.protocol.httpcontext; import org.apache.http.util.entityutils; import org.springframework.stereotype.component; import java.io.bytearrayinputstream; import java.io.ioexception; import java.io.inputstream; import java.nio.charset.standardcharsets; import java.util.locale; /** * 重写apachehttp请求处理逻辑,实现mock功能 */ @component public class mockapachehttprecoder implements proxyrecode { @sneakythrows @proxyrecodecfg(proxyclassname="org.apache.http.impl.client.closeablehttpclient", method="execute", type = recodetype.before) public static closeablehttpresponse executeproxy1(httpurirequest request, httpcontext context) { string path = request.geturi().tostring(); if (request instanceof httpentityenclosingrequestbase) { //post请求读取body httpentity entity = ((httpentityenclosingrequestbase)request).getentity(); if (entity == null) { return null; } string reqbody = entityutils.tostring(entity, standardcharsets.utf_8); } if (path.startswith("http://baidu.com")) { return buildmockresponse("{\"code\":\"200\", \"msg\":\"mock data\"}", null); } return null; } @sneakythrows @proxyrecodecfg(proxyclassname="org.apache.http.impl.client.closeablehttpclient", method="execute", type = recodetype.before) public static closeablehttpresponse executeproxy2(httphost target, httprequest request, httpcontext context) { string path = request.getrequestline().geturi(); if (request instanceof httpentityenclosingrequestbase) { //post请求读取body httpentity entity = ((httpentityenclosingrequestbase)request).getentity(); if (entity == null) { return null; } string reqbody = entityutils.tostring(entity, standardcharsets.utf_8); } if (path.startswith("http://baidu.com")) { return buildmockresponse("{\"code\":\"200\", \"msg\":\"mock返回\"}", null); } return null; } public static closeablehttpresponse buildmockresponse(string mockvalue, header[] headers) { protocolversion protocolversion = new protocolversion("http", 1, 1); string reasonphrase = "ok"; statusline statusline = new basicstatusline(protocolversion, httpstatus.sc_ok, reasonphrase); mockcloseablehttpresponse mockresponse = new mockcloseablehttpresponse(statusline); basichttpentity entity = new basichttpentity(); inputstream inputstream = new bytearrayinputstream(mockvalue.getbytes()); entity.setcontent(inputstream); entity.setcontentlength(mockvalue.length()); entity.setchunked(false); mockresponse.setentity(entity); if (headers != null) { mockresponse.setheaders(headers); } return mockresponse; } public static class mockcloseablehttpresponse extends basichttpresponse implements closeablehttpresponse { public mockcloseablehttpresponse(statusline statusline, reasonphrasecatalog catalog, locale locale) { super(statusline, catalog, locale); } public mockcloseablehttpresponse(statusline statusline) { super(statusline); } public mockcloseablehttpresponse(protocolversion ver, int code, string reason) { super(ver, code, reason); } @override public void close() throws ioexception { } } }
我们在springboot启动后请求试试
@springbootapplication public class appmain { @sneakythrows public static void main(string[] args) { springapplication.run(appmain.class, args); //创建httpclient对象 closeablehttpclient httpclient = httpclients.createdefault(); //创建请求对象 httpget httpget = new httpget("http://baidu.com"); //发送请求,请求响应结果 closeablehttpresponse response = httpclient.execute(httpget); //获取服务器返回的状态码 int statuscode = response.getstatusline().getstatuscode(); system.out.println(">>>>>>>>>服务端返回成功的状态码为:"+statuscode); httpentity entity = response.getentity(); string body = entityutils.tostring(entity); system.out.println(">>>>>>>>>服务端返回的数据为:"+body); //关闭资源 response.close(); httpclient.close(); } }
启动服务,在控制台可以看到打印了对org.apache.http.impl.client.closeablehttpclient类做字节码重写
[attach listener] info i.g.p.transformer.recodertransformer -[proxy-agent] rewrite class:[org.apache.http.impl.client.closeablehttpclient]
[attach listener] info io.github.proxy.agentmain -[proxy-agent] redefine loaded class complete, cost:171ms
springboot启动后请求baidu.com,得到结果,顺利得到了我们需要的测试数据
我们调整下代码,new httpget("http://zhihu.com"),换一个请求地址,然后发起请求
执行了httpclient的原始逻辑,请求zhihu.com拿到了响应。
简单试验就到这里了,其他用法可以按照github上readme指引试验一下。觉的这个小工具不错小伙伴可以点个star~
到此这篇关于使用java agent修改字节码,并在springboot启动时自动生效的文章就介绍到这了,更多相关java agent修改字节码内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论