1.json转换工具
package com.taotao.utils; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper;/** * json转换工具类 */publicclassJsonUtils{// 定义jackson对象 privatestaticfinalObjectMapper MAPPER =newObjectMapper();/** * 将对象转换成json字符串。 *
Title: pojoToJson
*Description:
*@paramdata *@return*/publicstaticString objectToJson(Object data) {try{ String string = MAPPER.writeValueAsString(data);returnstring; }catch(JsonProcessingException e) { e.printStackTrace(); }returnnull; }/** * 将json结果集转化为对象 *@paramjsonData json数据 *@paramclazz 对象中的object类型 *@return*/publicstatic T jsonToPojo(String jsonData,ClassbeanType){try{ T t = MAPPER.readValue(jsonData, beanType);returnt; }catch(Exceptione) { e.printStackTrace(); }returnnull; }/** * 将json数据转换成pojo对象list *Title: jsonToList
*Description:
*@paramjsonData *@parambeanType *@return*/publicstaticList jsonToList(String jsonData,ClassbeanType){ JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);try{Listlist= MAPPER.readValue(jsonData, javaType); .returnlist; }catch(Exceptione) { . e.printStackTrace(); }returnnull; } }
2.cookie的读写
package com.taotao.common.utils;importjava.io.UnsupportedEncodingException;importjava.net.URLDecoder;importjava.net.URLEncoder;importjavax.servlet.http.Cookie;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;/** *.* Cookie 工具类 **/publicfinalclassCookieUtils{/** *得到Cookie的值, 不编码 . ** @param request .* @param cookieName *@return */publicstaticStringgetCookieValue(HttpServletRequest request,StringcookieName) {returngetCookieValue(request, cookieName,false); }/** . *得到Cookie的值,* *@param request * @param cookieName* @return . */publicstaticStringgetCookieValue(HttpServletRequest request,StringcookieName, boolean isDecoder) { Cookie[] cookieList = request.getCookies();if(cookieList ==null|| cookieName ==null) {returnnull; }StringretValue =null;try{for(inti =0; i < cookieList.length; i++) { .if(cookieList[i].getName().equals(cookieName)) {if(isDecoder) { retValue = URLDecoder.decode(cookieList[i].getValue(),"UTF-8"); }else{ retValue = cookieList[i].getValue(); }break; } } }catch(UnsupportedEncodingException e) { e.printStackTrace(); }returnretValue; }/** * 得到Cookie的值, **@param request* @param cookieName *@return */publicstaticStringgetCookieValue(HttpServletRequest request,StringcookieName,StringencodeString) { Cookie[] cookieList = request.getCookies();if(cookieList ==null|| cookieName ==null) {returnnull; }StringretValue =null;try{for(inti =0; i < cookieList.length; i++) {if(cookieList[i].getName().equals(cookieName)) { retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);break; } } }catch(UnsupportedEncodingException e) { e.printStackTrace(); }returnretValue; }/** *设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码 */publicstaticvoidsetCookie(HttpServletRequest request, HttpServletResponse response,StringcookieName,StringcookieValue) { setCookie(request, response, cookieName, cookieValue,-1); . }/** *设置Cookie的值 在指定时间内生效,但不编码 */publicstaticvoidsetCookie(HttpServletRequest request, HttpServletResponse response,StringcookieName,StringcookieValue,intcookieMaxage) { setCookie(request, response, cookieName, cookieValue, cookieMaxage,false); }/** *设置Cookie的值 不设置生效时间,但编码 */publicstaticvoidsetCookie(HttpServletRequest request, HttpServletResponse response,StringcookieName,StringcookieValue, boolean isEncode) { setCookie(request, response, cookieName, cookieValue,-1, isEncode); }/** *设置Cookie的值 在指定时间内生效, 编码参数 */publicstaticvoidsetCookie(HttpServletRequest request, HttpServletResponse response,StringcookieName,StringcookieValue,intcookieMaxage, boolean isEncode) { doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode); }/** *设置Cookie的值 在指定时间内生效, 编码参数(指定编码) */publicstaticvoidsetCookie(HttpServletRequest request, HttpServletResponse response,StringcookieName,StringcookieValue,intcookieMaxage,StringencodeString) { doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString); }/** *删除Cookie带cookie域名 */publicstaticvoiddeleteCookie(HttpServletRequest request, HttpServletResponse response,StringcookieName) { doSetCookie(request, response, cookieName,"",-1,false); }/** *设置Cookie的值,并使其在指定时间内生效* *@param cookieMaxage cookie生效的最大秒数 */privatestaticfinalvoiddoSetCookie(HttpServletRequest request, HttpServletResponse response,StringcookieName,StringcookieValue,intcookieMaxage, boolean isEncode) {try{if(cookieValue ==null) { cookieValue =""; }elseif(isEncode) { cookieValue = URLEncoder.encode(cookieValue,"utf-8"); } Cookie cookie =newCookie(cookieName, cookieValue);if(cookieMaxage >0) cookie.setMaxAge(cookieMaxage);if(null!= request) {// 设置域名的cookie StringdomainName = getDomainName(request); System.out.println(domainName);if(!"localhost".equals(domainName)) { cookie.setDomain(domainName); } } cookie.setPath("/"); response.addCookie(cookie); }catch(Exception e) { e.printStackTrace(); } }/** *设置Cookie的值,并使其在指定时间内生效* *@param cookieMaxage cookie生效的最大秒数 */privatestaticfinalvoiddoSetCookie(HttpServletRequest request, HttpServletResponse response,StringcookieName,StringcookieValue,intcookieMaxage,StringencodeString) {try{if(cookieValue ==null) { cookieValue =""; }else{ cookieValue = URLEncoder.encode(cookieValue, encodeString); } Cookie cookie =newCookie(cookieName, cookieValue);if(cookieMaxage >0) cookie.setMaxAge(cookieMaxage);if(null!= request) {// 设置域名的cookie StringdomainName = getDomainName(request); System.out.println(domainName);if(!"localhost".equals(domainName)) { cookie.setDomain(domainName); } } cookie.setPath("/"); response.addCookie(cookie); }catch(Exception e) { e.printStackTrace(); } }/** *得到cookie的域名 */privatestaticfinalStringgetDomainName(HttpServletRequest request) {StringdomainName =null;StringserverName = request.getRequestURL().toString();if(serverName ==null|| serverName.equals("")) { domainName =""; }else{ serverName = serverName.toLowerCase(); serverName = serverName.substring(7);finalintend = serverName.indexOf("/"); serverName = serverName.substring(0, end);finalString[] domains = serverName.split("\\.");intlen = domains.length;if(len >3) {// www.xxx.com.cn domainName ="."+ domains[len -3] +"."+ domains[len -2] +"."+ domains[len -1]; }elseif(len <=3&& len >1) {// xxx.com or xxx.cn domainName ="."+ domains[len -2] +"."+ domains[len -1]; }else{ domainName = serverName; } }if(domainName !=null&& domainName.indexOf(":") >0) {String[] ary = domainName.split("\\:"); domainName = ary[0]; }returndomainName; } }
3.HttpClientUtil
packagecom.taotao.utils;importjava.io.IOException;importjava.net.URI;importjava.util.ArrayList;importjava.util.List;importjava.util.Map;importorg.apache.http.NameValuePair;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.client.utils.URIBuilder;importorg.apache.http.entity.ContentType;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.message.BasicNameValuePair;importorg.apache.http.util.EntityUtils;publicclass HttpClientUtil {publicstaticStringdoGet(Stringurl, Map param) {// 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault();StringresultString =""; CloseableHttpResponse response =null;try{// 创建uri URIBuilder builder = new URIBuilder(url); if(param !=null) {for(Stringkey: param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build();// 创建http GET请求 HttpGet httpGet = new HttpGet(uri); // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(),"UTF-8"); } }catch(Exception e) { e.printStackTrace(); }finally{try{if(response !=null) { response.close(); } httpclient.close(); }catch(IOException e) { e.printStackTrace(); } }returnresultString; }publicstaticStringdoGet(Stringurl) {returndoGet(url,null); }publicstaticStringdoPost(Stringurl, Map param) {// 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response =null;StringresultString ="";try{// 创建Http Post请求 HttpPost httpPost =newHttpPost(url);// 创建参数列表 if(param !=null) { List paramList =newArrayList<>();for(Stringkey: param.keySet()) { paramList.add(newBasicNameValuePair(key, param.get(key))); }// 模拟表单 UrlEncodedFormEntity entity =newUrlEncodedFormEntity(paramList); httpPost.setEntity(entity); }// 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(),"utf-8"); }catch(Exception e) { e.printStackTrace(); . }finally{try{ response.close(); }catch(IOException e) {// TODO Auto-generated catch block e.printStackTrace(); } }returnresultString; }publicstaticStringdoPost(Stringurl) {returndoPost(url,null); }publicstaticStringdoPostJson(Stringurl,Stringjson) {// 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response =null;StringresultString ="";try{// 创建Http Post请求 HttpPost httpPost =newHttpPost(url);// 创建请求内容 StringEntity entity =newStringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity);// 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(),"utf-8"); }catch(Exception e) { e.printStackTrace(); }finally{try{ response.close(); }catch(IOException e) {// TODO Auto-generated catch block e.printStackTrace(); } }returnresultString; } }
4.FastDFSClient工具类
packagecn.itcast.fastdfs.cliennt;importorg.csource.common.NameValuePair;importorg.csource.fastdfs.ClientGlobal;importorg.csource.fastdfs.StorageClient1;importorg.csource.fastdfs.StorageServer;importorg.csource.fastdfs.TrackerClient;importorg.csource.fastdfs.TrackerServer;publicclass FastDFSClient {privateTrackerClient trackerClient =null;privateTrackerServer trackerServer =null;privateStorageServer storageServer =null;privateStorageClient1 storageClient =null;publicFastDFSClient(Stringconf)throwsException {if(conf.contains("classpath:")) { conf = conf.replace("classpath:",this.getClass().getResource("/").getPath()); } ClientGlobal.init(conf); trackerClient =newTrackerClient(); trackerServer = trackerClient.getConnection(); storageServer =null; storageClient =newStorageClient1(trackerServer, storageServer); }/** * 上传文件方法
* <p>Title: uploadFile</p>
* <p>Description: </p>
* @param fileName 文件全路径
* @param extName 文件扩展名,不包含(.)
* @param metas 文件扩展信息 * @return * @throws Exception */publicStringuploadFile(StringfileName,StringextName, NameValuePair[] metas)throwsException {Stringresult = storageClient.upload_file1(fileName, extName, metas);returnresult; }publicStringuploadFile(StringfileName)throwsException {returnuploadFile(fileName,null,null); }publicStringuploadFile(StringfileName,StringextName)throwsException {returnuploadFile(fileName, extName,null); }/** * 上传文件方法
* <p>Title: uploadFile</p>
* <p>Description: </p>
* @param fileContent 文件的内容,字节数组
* @param extName 文件扩展名
* @param metas 文件扩展信息
* @return
* @throws Exception */publicStringuploadFile(byte[] fileContent,StringextName, NameValuePair[] metas)throwsException {Stringresult = storageClient.upload_file1(fileContent, extName, metas);returnresult; }publicStringuploadFile(byte[] fileContent)throwsException {returnuploadFile(fileContent,null,null); }publicStringuploadFile(byte[] fileContent,StringextName)throwsException {returnuploadFile(fileContent, extName,null); } } publicclass FastDFSTest { @TestpublicvoidtestFileUpload()throwsException {// 1、加载配置文件,配置文件中的内容就是tracker服务的地址。 ClientGlobal.init("D:/workspaces-itcast/term197/taotao-manager-web/src/main/resources/resource/client.conf");// 2、创建一个TrackerClient对象。直接new一个。 TrackerClient trackerClient =newTrackerClient();// 3、使用TrackerClient对象创建连接,获得一个TrackerServer对象。 TrackerServer trackerServer = trackerClient.getConnection();// 4、创建一个StorageServer的引用,值为null StorageServer storageServer =null;// 5、创建一个StorageClient对象,需要两个参数TrackerServer对象、StorageServer的引用 StorageClient storageClient =newStorageClient(trackerServer, storageServer);// 6、使用StorageClient对象上传图片。 //扩展名不带“.” String[] strings = storageClient.upload_file("D:/Documents/Pictures/images/200811281555127886.jpg","jpg",null);// 7、返回数组。包含组名和图片的路径。 for(Stringstring : strings) { System.out.println(string); } } } # ![image](http://upload-images.jianshu.io/upload_images/2509688-45370c9d24b87e31?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
5.获取异常的堆栈信息
packagecom.taotao.utils;importjava.io.PrintWriter;importjava.io.StringWriter;publicclassExceptionUtil{/** * 获取异常的堆栈信息 * *@paramt *@return*/publicstaticStringgetStackTrace(Throwable t){ StringWriter sw =newStringWriter(); PrintWriter pw =newPrintWriter(sw);try{ t.printStackTrace(pw);returnsw.toString(); }finally{ pw.close(); } } }
#6.easyUIDataGrid对象返回值
packagecom.taotao.result;importjava.util.List;/** * easyUIDataGrid对象返回值 *
Title: EasyUIResult
*Description:
*Company: www.itcast.com
*@author入云龙 *@date2019年7月21日下午4:12:52 *@version1.0 */publicclassEasyUIResult{privateInteger total;privateList rows;publicEasyUIResult(Integer total, List<?> rows){this.total = total;this.rows = rows; }publicEasyUIResult(longtotal, List rows){this.total = (int) total;this.rows = rows; }publicIntegergetTotal(){returntotal; }publicvoidsetTotal(Integer total){this.total = total; }publicList getRows() {returnrows; }publicvoidsetRows(List<?> rows){this.rows = rows; } }
7.ftp上传下载工具类
package com.taotao.utils;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importorg.apache.commons.net.ftp.FTP;importorg.apache.commons.net.ftp.FTPClient;importorg.apache.commons.net.ftp.FTPFile;importorg.apache.commons.net.ftp.FTPReply;/** *ftp上传下载工具类 *
Title: FtpUtil
* <p>Description: </p> *Company: www.itcast.com
* @author 入云龙* @date 2015年7月29日下午8:11:51 *@version 1.0 */publicclassFtpUtil{/** *Description: 向FTP服务器上传文件* @param host FTP服务器hostname *@param port FTP服务器端口 * @param username FTP登录账号* @param password FTP登录密码 *@param basePath FTP服务器基础目录 * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath* @param filename 上传到FTP服务器上的文件名 * @param input 输入流* @return 成功返回true,否则返回false */publicstaticboolean uploadFile(Stringhost,intport,Stringusername,Stringpassword,StringbasePath,StringfilePath,Stringfilename, InputStream input) { boolean result =false; FTPClient ftp =newFTPClient();try{intreply; ftp.connect(host, port);// 连接FTP服务器 // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器 ftp.login(username, password);// 登录 reply = ftp.getReplyCode(); if(!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect();returnresult; }//切换到上传目录 if (!ftp.changeWorkingDirectory(basePath+filePath)) { //如果目录不存在创建目录 String[] dirs = filePath.split("/"); StringtempPath = basePath;for(Stringdir : dirs) {if(null== dir ||"".equals(dir))continue; tempPath +="/"+ dir;if(!ftp.changeWorkingDirectory(tempPath)) {if(!ftp.makeDirectory(tempPath)) {returnresult; }else{ ftp.changeWorkingDirectory(tempPath); } } } }//设置上传文件的类型为二进制类型 ftp.setFileType(FTP.BINARY_FILE_TYPE);//上传文件 if(!ftp.storeFile(filename, input)) {returnresult; . } input.close(); ftp.logout(); result =true; }catch(IOException e) { e.printStackTrace(); }finally{if(ftp.isConnected()) {try{ ftp.disconnect(); }catch(IOException ioe) { } } }returnresult; }/** *Description: 从FTP服务器下载文件 * @param host FTP服务器hostname* @param port FTP服务器端口 *@param username FTP登录账号* @param password FTP登录密码 *@param remotePath FTP服务器上的相对路径* @param fileName 要下载的文件名 . *@param localPath 下载后保存到本地的路径* @return */publicstaticboolean downloadFile(Stringhost,intport,Stringusername,Stringpassword,StringremotePath,StringfileName,StringlocalPath) { boolean result =false; FTPClient ftp =newFTPClient();try{intreply; ftp.connect(host, port);// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器 ftp.login(username, password);// 登录 reply = ftp.getReplyCode(); if(!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect();returnresult; } ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录 FTPFile[] fs = ftp.listFiles();for(FTPFile ff : fs) {if(ff.getName().equals(fileName)) { File localFile =newFile(localPath +"/"+ ff.getName()); OutputStreamis=newFileOutputStream(localFile); ftp.retrieveFile(ff.getName(),is);is.close(); } } ftp.logout(); result =true; }catch(IOException e) { e.printStackTrace(); }finally{if(ftp.isConnected()) {try{ ftp.disconnect(); }catch(IOException ioe) { } } }returnresult; } publicstaticvoidmain(String[] args) {try{ FileInputStreamin=newFileInputStream(newFile("D:\\temp\\image\\gaigeming.jpg"));147.boolean flag = uploadFile("192.168.25.133",21,"ftpuser","ftpuser","/home/ftpuser/www/images","/2015/01/21","gaigeming.jpg",in); System.out.println(flag); }catch(FileNotFoundException e) { e.printStackTrace(); } } }
8.各种id生成策略
packagecom.taotao.utils;importjava.util.Random;/** * 各种id生成策略 * <p>Title: IDUtils</p> * <p>Description: </p>
* @date 2015年7月22日下午2:32:10 * @version 1.0 */publicclass IDUtils {/** * 图片名生成 */publicstaticStringgenImageName() {//取当前时间的长整形值包含毫秒 longmillis= System.currentTimeMillis();//long millis = System.nanoTime(); //加上三位随机数 Randomrandom=newRandom();intend3 =random.nextInt(999);//如果不足三位前面补0 Stringstr=millis+String.format("%03d", end3);returnstr; }/** * 商品id生成 */publicstaticlonggenItemId() {//取当前时间的长整形值包含毫秒 long millis = System.currentTimeMillis(); //long millis = System.nanoTime(); //加上两位随机数 Randomrandom=newRandom();intend2 =random.nextInt(99);//如果不足两位前面补0 Stringstr=millis+String.format("%02d", end2);longid =newLong(str);returnid; }publicstaticvoidmain(String[] args) {for(inti=0;i<100;i++) System.out.println(genItemId()); } }
##9.上传图片返回值
packagecom.result;/** * 上传图片返回值 *
Title: PictureResult
*Description:
*Company: www.itcast.com
*@author入云龙 *@date2015年7月22日下午2:09:02 *@version1.0 */publicclassPictureResult{/** * 上传图片返回值,成功:0 失败:1 */privateIntegererror;/** * 回显图片使用的url */privateString url;/** * 错误时的错误消息 */privateString message;publicPictureResult(Integer state, String url){this.url = url;this.error= state; }publicPictureResult(Integer state, String url, String errorMessage){this.url = url;this.error= state;this.message = errorMessage; }publicIntegergetError(){returnerror; }publicvoidsetError(Integererror){this.error=error; }publicStringgetUrl(){returnurl; }publicvoidsetUrl(String url){this.url = url; }publicStringgetMessage(){returnmessage; }publicvoidsetMessage(String message){this.message = message; } }
10.自定义响应结构
packagecom.result;importjava.util.List;importcom.fasterxml.jackson.databind.JsonNode;importcom.fasterxml.jackson.databind.ObjectMapper;/** * 自定义响应结构 */publicclassTaotaoResult{// 定义jackson对象 privatestaticfinalObjectMapper MAPPER = new ObjectMapper();// 响应业务状态 private Integer status; // 响应消息 private String msg; // 响应中的数据 private Object data; publicstatic TaotaoResult build(Integer status, String msg, Objectdata) {returnnew TaotaoResult(status, msg,data); }publicstatic TaotaoResult ok(Objectdata) {returnnew TaotaoResult(data); }publicstatic TaotaoResult ok() {returnnew TaotaoResult(null); }publicTaotaoResult() { }publicstatic TaotaoResult build(Integer status, String msg) {returnnew TaotaoResult(status, msg,null); }publicTaotaoResult(Integer status, String msg, Objectdata) {this.status = status;this.msg = msg;this.data=data; }publicTaotaoResult(Objectdata) {this.status =200;this.msg ="OK";this.data=data; }// public Boolean isOK() { . // return this.status == 200; // } publicInteger getStatus() {returnstatus; }publicvoid setStatus(Integer status) {this.status = status; }publicString getMsg() {returnmsg; }publicvoid setMsg(String msg) {this.msg = msg; }publicObject getData() {returndata; }publicvoid setData(Objectdata) {this.data=data; }/** * 将json结果集转化为TaotaoResult对象 * *@paramjsonData json数据 *@paramclazz TaotaoResult中的object类型 *@return*/publicstatic TaotaoResult formatToPojo(String jsonData, Class clazz) {try{if(clazz ==null) {returnMAPPER.readValue(jsonData, TaotaoResult.class); } JsonNode jsonNode = MAPPER.readTree(jsonData); JsonNodedata= jsonNode.get("data"); Object obj =null;if(clazz !=null) {if(data.isObject()) { obj = MAPPER.readValue(data.traverse(), clazz); }elseif(data.isTextual()) { obj = MAPPER.readValue(data.asText(), clazz); } }returnbuild(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj); }catch(Exception e) {returnnull; } }/** * 没有object对象的转化 * *@paramjson *@return*/publicstatic TaotaoResult format(String json) {try{returnMAPPER.readValue(json, TaotaoResult.class); }catch(Exception e) { e.printStackTrace(); }returnnull; }/** * Object是集合转化 * *@paramjsonData json数据 *@paramclazz 集合中的类型 *@return*/publicstatic TaotaoResult formatToList(String jsonData, Class clazz) {try{ JsonNode jsonNode = MAPPER.readTree(jsonData); JsonNodedata= jsonNode.get("data"); Object obj =null;if(data.isArray() &&data.size() >0) { obj = MAPPER.readValue(data.traverse(), MAPPER.getTypeFactory().constructCollectionType(List.class, clazz)); }returnbuild(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj); }catch(Exception e) {returnnull; } } }
##11.jedis操作
packagecom.taotao.jedis;publicinterface JedisClient {Stringset(Stringkey,Stringvalue);Stringget(Stringkey); Boolean exists(Stringkey); Long expire(Stringkey,intseconds); Long ttl(Stringkey); Long incr(Stringkey); Long hset(Stringkey,Stringfield,Stringvalue);Stringhget(Stringkey,Stringfield); Long hdel(Stringkey,String... field); }packagecom.taotao.jedis;importorg.springframework.beans.factory.annotation.Autowired;importredis.clients.jedis.JedisCluster;publicclass JedisClientCluster implements JedisClient { @AutowiredprivateJedisCluster jedisCluster; @OverridepublicStringset(Stringkey,Stringvalue) {returnjedisCluster.set(key, value); } @OverridepublicStringget(Stringkey) {returnjedisCluster.get(key); } @OverridepublicBoolean exists(Stringkey) {returnjedisCluster.exists(key); } @OverridepublicLong expire(Stringkey,intseconds) {returnjedisCluster.expire(key, seconds); } @OverridepublicLong ttl(Stringkey) {returnjedisCluster.ttl(key); } @OverridepublicLong incr(Stringkey) {returnjedisCluster.incr(key); } @OverridepublicLong hset(Stringkey,Stringfield,Stringvalue) {returnjedisCluster.hset(key, field, value); } @OverridepublicStringhget(Stringkey,Stringfield) {returnjedisCluster.hget(key, field); } @OverridepublicLong hdel(Stringkey,String... field) {returnjedisCluster.hdel(key, field); } }packagecom.taotao.jedis;importorg.springframework.beans.factory.annotation.Autowired;importredis.clients.jedis.Jedis;importredis.clients.jedis.JedisPool;publicclass JedisClientPool implements JedisClient { @AutowiredprivateJedisPool jedisPool; @OverridepublicStringset(Stringkey,Stringvalue) { Jedis jedis = jedisPool.getResource();Stringresult = jedis.set(key, value); jedis.close();returnresult; } @OverridepublicStringget(Stringkey) { Jedis jedis = jedisPool.getResource();Stringresult = jedis.get(key); jedis.close();returnresult; } @OverridepublicBoolean exists(Stringkey) { Jedis jedis = jedisPool.getResource(); Boolean result = jedis.exists(key); jedis.close();returnresult; } @OverridepublicLong expire(Stringkey,intseconds) { Jedis jedis = jedisPool.getResource(); Long result = jedis.expire(key, seconds); jedis.close();returnresult; } @OverridepublicLong ttl(Stringkey) { Jedis jedis = jedisPool.getResource(); Long result = jedis.ttl(key); jedis.close();returnresult; } @OverridepublicLong incr(Stringkey) { Jedis jedis = jedisPool.getResource(); Long result = jedis.incr(key); jedis.close();returnresult; } @OverridepublicLong hset(Stringkey,Stringfield,Stringvalue) { Jedis jedis = jedisPool.getResource(); Long result = jedis.hset(key, field, value); jedis.close();returnresult; } @OverridepublicStringhget(Stringkey,Stringfield) { Jedis jedis = jedisPool.getResource();Stringresult = jedis.hget(key, field); jedis.close();returnresult; } @OverridepublicLong hdel(Stringkey,String... field) { Jedis jedis = jedisPool.getResource(); Long result = jedis.hdel(key, field); jedis.close();returnresult; } }