springboot中通过lua脚本来获取序列号的方法
程序员文章站
2022-05-30 14:39:28
序言:事件:此web项目的功能及其简单,就是有客户端来访问redis序列号服务时发送jison报文,项目已经在测试环境成功运行2周了,具体的代码我就直接上了,此博客仅是自己的记录,同学们可做参考!一、...
序言:
事件:此web项目的功能及其简单,就是有客户端来访问redis序列号服务时发送jison报文,项目已经在测试环境成功运行2周了,具体的代码我就直接上了,此博客仅是自己的记录,同学们可做参考!
一、工程目录结构
二、配置文件
1、pom.xml
<?xml version="1.0" encoding="utf-8"?> <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <parent> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-parent</artifactid> <version>2.2.6.release</version> <relativepath/> <!-- lookup parent from repository --> </parent> <groupid>com.test</groupid> <artifactid>seq-gen</artifactid> <version>0.0.1-snapshot</version> <name>seq-gen</name> <description>generate sequence from redis</description> <properties> <project.build.sourceencoding>utf-8</project.build.sourceencoding> <project.reporting.outputencoding>utf-8</project.reporting.outputencoding> <java.version>1.8</java.version> </properties> <dependencies> <!--引入日志依赖--> <!--<dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-log4j12</artifactid> <version>1.7.21</version> </dependency> <dependency> <groupid>commons-logging</groupid> <artifactid>commons-logging</artifactid> <version>1.2</version> </dependency>--> <!-- log4j2的api、core和web包 --> <dependency> <groupid>org.apache.logging.log4j</groupid> <artifactid>log4j-api</artifactid> <version>2.11.1</version> </dependency> <dependency> <groupid>org.apache.logging.log4j</groupid> <artifactid>log4j-core</artifactid> <version>2.11.1</version> </dependency> <dependency> <groupid>org.apache.logging.log4j</groupid> <artifactid>log4j-web</artifactid> <version>2.11.1</version> </dependency> <!-- slf4j与log4j2的连接包 --> <dependency> <groupid>org.apache.logging.log4j</groupid> <artifactid>log4j-slf4j-impl</artifactid> <version>2.11.1</version> </dependency> <!-- log4j与log4j2的连接包 --> <dependency> <groupid>org.apache.logging.log4j</groupid> <artifactid>log4j-1.2-api</artifactid> <version>2.11.1</version> </dependency> <!-- log4j2支撑完全异步模式的关键api --> <dependency> <groupid>com.lmax</groupid> <artifactid>disruptor</artifactid> <version>3.4.2</version> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-api</artifactid> <version>1.7.21</version> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-redis</artifactid> </dependency> <dependency> <groupid>com.alibaba</groupid> <artifactid>fastjson</artifactid> <version>1.2.62</version> </dependency> <dependency> <groupid>redis.clients</groupid> <artifactid>jedis</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter</artifactid> <exclusions> <exclusion> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-logging</artifactid> </exclusion> </exclusions> </dependency> <!-- 热部署,集成测试--> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-devtools</artifactid> <optional>true</optional> </dependency> <dependency> <groupid>org.projectlombok</groupid> <artifactid>lombok</artifactid> <optional>true</optional> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-compiler-plugin</artifactid> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-maven-plugin</artifactid> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-surefire-plugin</artifactid> <version>2.4.2</version> <configuration> <skiptests>true</skiptests> </configuration> </plugin> </plugins> </build> </project>
2、applicaiton.properties
spring.redis.database= 0 spring.redis.host= 127.0.0.1 spring.redis.port= 6379 spring.redis.pool.max-active= 8 spring.redis.pool.max-wait= -1ms spring.redis.pool.max-idle= 8 spring.redis.pool.min-idle= 0 spring.redis.pool.timeout= 2000ms server.port= 8085
3、luascripts脚本
local function get_next_seq() --keys[1]:第一个参数代表存储序列号的key 相当于代码中的业务类型 local key = tostring(keys[1]) --keys[2]:第二个参数代表序列号增长速度 local incr_amoutt = tonumber(keys[2]) --keys[3]`:第四个参数为序列号 (yymmddhhmmsssss + 两位随机数) local seq = tonumber(keys[3]) --序列号过期时间大小,单位是秒 -- local month_in_seconds = 24 * 60 * 60 * 7 --redis的 setnx 命令可以实现分布式锁,用于解决高并发 --如果key不存在,将 key 的值设为 seq,设置成成功返回1 未设置返回0 --若给定的 key 已经存在,则 setnx 不做任何动作,获取下一个按照步增的值 if (1 == redis.call('setnx', key, seq)) --不存在key, then --设置key的生存时间 为 month_in_seconds秒 -- 由于序列号需要永久有效,不能过期,所以取消这个设置,需要的可以取消注释 -- redis.call('expire', key, month_in_seconds) --将序列返回给调用者 return seq else --key值存在,直接获取下一个增加的值 local nextseq = redis.call('incrby', key, incr_amoutt) return nextseq end end return get_next_seq()
4、log4j2.xml
<?xml version="1.0" encoding="utf-8"?> <!--日志级别以及优先级排序: off > fatal > error > warn > info > debug > trace > all --> <!--configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出--> <!--monitorinterval:log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数--> <configuration status="info" monitorinterval="30" packages="org.apache.logging.log4j.core.layout"> <properties> <property name="basedir">logs</property> </properties> <!--先定义所有的appender--> <appenders> <!-- 这个输出控制台的配置 --> <console name="console" target="system_out"> <!-- 控制台只输出level及以上级别的信息(onmatch),其他的直接拒绝(onmismatch) --> <thresholdfilter level="info" onmatch="accept" onmismatch="deny"/> <!-- 这个都知道是输出日志的格式 --> <patternlayout pattern="[%date{default}]-[%highlight{%level}]-[%threadname]-[%-class{4}:%line]-%msg%n"/> </console> <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档--> <rollingfile name="rollingfileinfo" filename="${basedir}/seq_all.log" filepattern="${basedir}/$${date:yyyy-mm}/all-%d{yyyy-mm-dd}-%i.log"> <!--控制台只输出level及以上级别的信息(onmatch),其他的直接拒绝(onmismatch)--> <thresholdfilter level="info" onmatch="accept" onmismatch="deny"/> <patternlayout pattern="[%date{default}]-[%highlight{%level}]-[%threadname]-[%-class{4}:%line]-%msg%n"/> <policies> <timebasedtriggeringpolicy/> <sizebasedtriggeringpolicy size="500 mb"/> </policies> </rollingfile> <rollingfile name="rollingfilewarn" filename="${basedir}/seq_warn.log" filepattern="${basedir}/$${date:yyyy-mm}/warn-%d{yyyy-mm-dd}-%i.log"> <thresholdfilter level="warn" onmatch="accept" onmismatch="deny"/> <patternlayout pattern="[%date{default}]-[%highlight{%level}]-[%threadname]-[%-class{4}:%line]-%msg%n"/> <policies> <timebasedtriggeringpolicy/> <sizebasedtriggeringpolicy size="100 mb"/> </policies> <!-- defaultrolloverstrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 --> <defaultrolloverstrategy max="20"/> </rollingfile> <rollingfile name="rollingfileerrorcommon" filename="${basedir}/seq_error.log" filepattern="${basedir}/$${date:yyyy-mm}/error-%d{yyyy-mm-dd}-%i.log"> <thresholdfilter level="error" onmatch="accept" onmismatch="deny"/> <patternlayout pattern="[%date{default}]-[%highlight{%level}]-[%threadname]-[%-class{4}:%line]-%msg%n"/> <policies> <timebasedtriggeringpolicy/> <sizebasedtriggeringpolicy size="100 mb"/> </policies> </rollingfile> </appenders> <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效--> <loggers> <!--过滤掉spring和mybatis的一些无用的debug信息--> <logger name="org.springframework" level="debug"></logger> <logger name="org.mybatis" level="debug"></logger> <logger name="com.alicl oud.openservices.tablestore" level="error" additivity="false"> <appender-ref ref="rollingfileotserror"/> </logger> <root level="info"> <appender-ref ref="console"/> <appender-ref ref="rollingfileinfo"/> <appender-ref ref="rollingfilewarn"/> <appender-ref ref="rollingfileerrorcommon"/> </root> </loggers> </configuration>
三、代码部分
1、启动类
package com.test; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.springbootapplication; @springbootapplication public class seqgenapplication { private static final logger log = loggerfactory.getlogger(seqgenapplication.class); public static void main(string[] args) { springapplication.run(seqgenapplication.class, args); log.info("start seqgenapplication sucessfully........"); } }
2、bean
package com.test.bean; import com.alibaba.fastjson.annotation.jsonfield; /** * copyright (c), 2019-2020 * * 此类是请求和响应中对应的属性 * * @author fanhf * @date 2020-03-25 * @version v1.0.0 */ public class rspbean { public rspbean(){} /* 开始序列号 */ @jsonfield(name = "snnumb") private integer snnumb; /* 从redis中获取的序列号 */ @jsonfield(name = "snnume") private integer snnume; /* 发起方操作流水 */ @jsonfield(name = "oprnumb") private string oprnumb; /* 落地方操作时间 */ @jsonfield(name = "oprtime") private string oprtime; /* 返回码 */ @jsonfield(name = "bizorderresult") private string bizorderresult; /* 返回码描述 */ @jsonfield(name = "resultdesc") private string resultdesc; public integer getsnnumb() { return snnumb; } public void setsnnumb(integer snnumb) { this.snnumb = snnumb; } public integer getsnnume() { return snnume; } public void setsnnume(integer snnume) { this.snnume = snnume; } public string getoprnumb() { return oprnumb; } public void setoprnumb(string oprnumb) { this.oprnumb = oprnumb; } public string getoprtime() { return oprtime; } public void setoprtime(string oprtime) { this.oprtime = oprtime; } public string getbizorderresult() { return bizorderresult; } public void setbizorderresult(string bizorderresult) { this.bizorderresult = bizorderresult; } public string getresultdesc() { return resultdesc; } public void setresultdesc(string resultdesc) { this.resultdesc = resultdesc; } @override public string tostring() { return "rspbean{" + "snnumb=" + snnumb + ", snnume=" + snnume + ", oprnumb='" + oprnumb + '\'' + ", oprtime='" + oprtime + '\'' + ", bizorderresult='" + bizorderresult + '\'' + ", resultdesc='" + resultdesc + '\'' + '}'; } }
3、controller
package com.test.controller; import com.test.bean.rspbean; import com.test.service.redisservice; import com.test.util.commonutils; import com.alibaba.fastjson.jsonobject; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.autowired; import org.springframework.data.redis.core.redistemplate; import org.springframework.web.bind.annotation.postmapping; import org.springframework.web.bind.annotation.requestbody; import org.springframework.web.bind.annotation.restcontroller; import java.util.hashmap; import java.util.map; /** * copyright (c), 2019-2020 * * 此类是web层的入口,用来接收json请求 * * @author fanhf * @date 2020-03-29 * @version v1.0.0 */ @restcontroller public class rediscontroller { private static final logger log = loggerfactory.getlogger(rediscontroller.class); @autowired private redistemplate<string, string> redistemplate; @autowired private redisservice redisservice; @postmapping(path = "/app/v1/sync/bizorder/queryserialnumber", consumes = "application/json", produces = "application/json") public string rcvreq(@requestbody string jsonparam){ string prettyjson= commonutils.prettyjson(jsonparam); log.info("receive requset: "); log.info("\r\n"+prettyjson); jsonobject jsonobject = new jsonobject(); rspbean rw = new rspbean(); string response = null; map<string ,string> jsonmap = new hashmap<string,string>(); try { // 将报文放入map中 jsonmap = commonutils.putreq2map(jsonparam); response = redisservice.createresponse(jsonmap); prettyjson = commonutils.prettyjson(response); log.info("send response: "); log.info("\r\n"+prettyjson); } catch (exception ex) { if (null == jsonobject || 0 == jsonobject.size()) { try { string oprnumb = jsonmap.get("oprnumb"); rw.setoprnumb(oprnumb); rw.setbizorderresult("30000"); rw.setresultdesc(ex.getmessage()); jsonobject json = (jsonobject) jsonobject.tojson(rw); response = json.tostring(); } catch (exception e) { e.printstacktrace(); } return response; } } return response; } }
4、service
package com.test.service; import java.util.map; public interface redisservice { string createresponse(map<string, string> jsonmap); }
serviceimpl
package com.test.service; import com.test.bean.rspbean; import com.test.util.commonutils; import com.test.util.redisutil; import com.alibaba.fastjson.jsonobject; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.stereotype.component; import org.springframework.stereotype.service; import org.springframework.util.stringutils; import java.util.*; /** * copyright (c), 2019-2020 * * 此类是service处理层,根据接收到的序列名称和步长值,从redis中获取序列号,再对返回的信息进行组装 * 以及对异常情况时返回数据的处理 * * @author fanhf * @date 2020-04-05 * @version v1.0.0 */ @component @service public class redisserviceimpl implements redisservice { private static final logger log = loggerfactory.getlogger(redisserviceimpl.class); @override public string createresponse(map<string, string> jsonmap) { string response = null; rspbean rw = null; jsonobject json = null; // 之所以要遍历map是因为怕传过来的key值有小写的,怕get不到对应的值 string key = null; string snnamevalue = null; string increamountvalue = null; for (map.entry<string, string> entry : jsonmap.entryset()) { key = entry.getkey(); if ("snname".equalsignorecase(key)) { snnamevalue = entry.getvalue(); } else if("snnum".equalsignorecase(key)){ increamountvalue = entry.getvalue(); } } string seq="0"; // 从redis中获取序列号(根据序列号名称和步长获取序列号) list<string> busilist = arrays.aslist(snnamevalue,increamountvalue,seq); long seqfromredis = null; try { seqfromredis = redisutil.getbusiseq(busilist); } catch (exception e) { log.error("cannot get seq from redis cluster ,please check redis cluster"+ "_" + e.getmessage(), e); } log.info("seqfromredis:{}", seqfromredis); string oprnumb = jsonmap.get("oprnumb"); string oprtime = commonutils.getcurdatetimestamp(); try { rw = new rspbean(); int snnumb; if(!stringutils.isempty(seqfromredis)){ snnumb=seqfromredis.intvalue(); rw.setsnnumb(snnumb); rw.setsnnume(snnumb+integer.parseint(increamountvalue)); rw.setbizorderresult("00000"); rw.setresultdesc("success"); }else{ rw.setsnnumb(0); rw.setsnnume(0); rw.setbizorderresult("30000"); rw.setresultdesc("business handles failed...."); } rw.setoprnumb(oprnumb); rw.setoprtime(oprtime); json = (jsonobject) jsonobject.tojson(rw); response = json.tostring(); } catch (exception e) { log.error("boxing response of json happend error "+ "_" + e.getmessage(), e); if (rw != null) { rw.setbizorderresult("30000"); rw.setresultdesc("business handles failed......"); json = (jsonobject) jsonobject.tojson(rw); response = json.tostring(); } log.info("send response: [ {} ]", response ); jsonmap.put("responsetowzw", response); return response; } return response; } }
5、utils
5.1 commonutils
package com.test.util; import com.alibaba.fastjson.json; import com.alibaba.fastjson.jsonobject; import com.alibaba.fastjson.serializer.serializerfeature; import org.slf4j.logger; import org.slf4j.loggerfactory; import java.text.dateformat; import java.text.simpledateformat; import java.time.localdatetime; import java.time.format.datetimeformatter; import java.util.date; import java.util.map; /** * 工具类 * @author fanhf * @date 2020-04-01 * @version v1.0.0 */ public class commonutils { private static final logger log = loggerfactory.getlogger(commonutils.class); public static map<string, string> putreq2map(string jsonparam) { // 将json字符串转换为json对象 return (map<string, string>) jsonobject.parse(jsonparam); } /** * @description 获取系统当前时间 * @return 时间字符串 */ public static string getcurdatetimestamp(){ datetimeformatter datetimeformatter=datetimeformatter.ofpattern("yyyymmddhhmmss"); localdatetime localdatetime = localdatetime.now(); string now=localdatetime.format(datetimeformatter); return now; } /** * 美化json格式,将一行json转为为有回车换行的json * @param reqjson * @return 美化后的json */ public static string prettyjson(string reqjson){ jsonobject object = jsonobject.parseobject(reqjson); string prettyjson = json.tojsonstring(object, serializerfeature.prettyformat, serializerfeature.writemapnullvalue,serializerfeature.writedateusedateformat); return prettyjson; } }
5.2 readconfigspathutil
package com.test.util; import org.slf4j.logger; import org.slf4j.loggerfactory; import java.io.bufferedreader; import java.io.file; import java.io.filereader; import java.io.ioexception; import java.util.properties; /** * @ description : 用来获取linux和windows的config的绝对路径 * @ author : fanhf * @ createdate : 2020/4/11 0:33 * @ updateuser : fanhf * @ updatedate : 2020/4/11 0:33 * @ updateremark : 修改内容 * @ version : 1.0.0 */ public class readconfigspathutil { private static final logger log = loggerfactory.getlogger(readconfigspathutil.class); private readconfigspathutil() {} private static properties properties = null; /** * @description 获取linux和windows系统中config的目录 * @param configpath lua脚本的相对路径 * @return linux和windows系统中config的目录的绝对路径 */ public static string getpropertiespath(string configpath) { string syspath = getrelativepath(); log.info("syspath:{}",syspath); string filepath = new stringbuffer(syspath) .append(file.separator) .append("config") .append(file.separator) .append(configpath).tostring(); log.info("filepath:{}",filepath); return filepath; } /** * @description 获取系统字符型属性 * @author add by fanhf * @date 2020-04-08 */ public static string getrelativepath() { return system.getproperty("user.dir"); } /** * @description 读取lua脚本的内容 * @param luascriptpath lua脚本的绝对路径 * @return 读取到的lua脚本的内容 * @author add by fanhf * @date 2020-04-15 */ public static string readfilecontent(string luascriptpath) { string filename = getpropertiespath(luascriptpath); file file = new file(filename); bufferedreader reader = null; stringbuffer sbf = new stringbuffer(); try { reader = new bufferedreader(new filereader(file)); string tempstr; while ((tempstr = reader.readline()) != null) { sbf.append(tempstr); sbf.append("\r\n"); } reader.close(); return sbf.tostring(); } catch (ioexception e) { e.printstacktrace(); } finally { if (reader != null) { try { reader.close(); } catch (ioexception e1) { e1.printstacktrace(); } } } return sbf.tostring(); } }
5.3 redisutil
package com.test.util; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.core.io.classpathresource; import org.springframework.core.io.support.encodedresource; import org.springframework.data.redis.core.stringredistemplate; import org.springframework.data.redis.core.script.defaultredisscript; import org.springframework.data.redis.core.script.defaultscriptexecutor; import org.springframework.data.redis.core.script.redisscript; import org.springframework.stereotype.component; import org.springframework.util.filecopyutils; import java.io.ioexception; import java.util.list; /** * @ description : 用来加载和读取lua脚本并加载 * @ author : fanhf * @ createdate : 2020/4/01 0:32 * @ updateuser : fanhf * @ updatedate : 2020/4/01 0:32 * @ updateremark : 修改内容 * @ version : 1.0.0 */ @component public class redisutil { private static final logger log = loggerfactory.getlogger(redisutil.class); private static stringredistemplate redisstringtemplate; private static redisscript<long> redisscript; private static defaultscriptexecutor<string> scriptexecutor; private redisutil(stringredistemplate template) throws ioexception { redisutil.redisstringtemplate = template; // 之所以会注释掉是由于这段代码可以直接读取resource目录下的非application.properties的文件, // 但是这个方法在生产和测试环境不适用,因为配置文件必须暴露初打的jar包里 // classpathresource luaresource = new classpathresource("luascript/genseq.lua"); // encodedresource encres = new encodedresource(luaresource, "utf-8"); // string luastring = filecopyutils.copytostring(encres.getreader()); string luastring = readconfigspathutil.readfilecontent("luascript/genseq.lua"); redisscript = new defaultredisscript<>(luastring, long.class); scriptexecutor = new defaultscriptexecutor<>(redisstringtemplate); } public static long getbusiseq(list<string> busilist) throws exception{ long seqfromredis = scriptexecutor.execute(redisscript, busilist); return seqfromredis; } }
总结
到此这篇关于springboot中通过lua脚本来获取序列号的文章就介绍到这了,更多相关springboot中通过lua脚本来获取序列号内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 鱼鳔的功效和食用禁忌都有哪些呢?