├── READ.ME ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── liu │ │ ├── Constants.java │ │ ├── code │ │ ├── BaseApiCode.java │ │ ├── CardApiCode.java │ │ └── FileUploadApiCode.java │ │ ├── core │ │ ├── AppSpringContext.java │ │ ├── JedisCallback.java │ │ ├── PipelineCallback.java │ │ ├── ServiceWrapper.java │ │ ├── dao │ │ │ ├── TOuInfoMapper.java │ │ │ ├── TUserMapper.java │ │ │ └── annotation │ │ │ │ └── IRepository.java │ │ └── entity │ │ │ ├── TOuInfo.java │ │ │ ├── TOuInfoExample.java │ │ │ ├── TUser.java │ │ │ └── TUserExample.java │ │ ├── custom │ │ └── annotation │ │ │ ├── FruitColor.java │ │ │ ├── FruitName.java │ │ │ ├── FruitProvider.java │ │ │ └── use │ │ │ ├── Apple.java │ │ │ ├── FruitMain.java │ │ │ └── FruitProcessUtil.java │ │ ├── elasticsearch │ │ ├── Blog.java │ │ ├── DataFactory.java │ │ ├── ElasticSearchHandler.java │ │ ├── JsonUtils.java │ │ └── search │ │ │ ├── BlogParam.java │ │ │ ├── BlogService.java │ │ │ ├── BlogServiceImpl.java │ │ │ ├── ElasticSearchQueryHandler.java │ │ │ └── ElasticSearchQueryUtils.java │ │ ├── enums │ │ └── MqSendType.java │ │ ├── exceptions │ │ ├── BaseException.java │ │ ├── BaseTradeException.java │ │ ├── BusinessException.java │ │ ├── MideaException.java │ │ ├── RedisClientException.java │ │ └── TradeSystemException.java │ │ ├── groovy │ │ ├── LoadConfigGroovy.groovy │ │ └── TestLoadConfigGroovyMain.java │ │ ├── kafka │ │ ├── KafkaClientMain.java │ │ ├── consumer │ │ │ └── KafkaConsumer.java │ │ └── producer │ │ │ └── KafkaProducer.java │ │ ├── mq │ │ └── MessageProducer.java │ │ ├── netty │ │ ├── HelloClient.java │ │ ├── HelloServer.java │ │ ├── client │ │ │ └── handler │ │ │ │ └── HelloClientIntHandler.java │ │ └── server │ │ │ └── handler │ │ │ └── HelloServerInHandler.java │ │ ├── request │ │ └── BaseRequest.java │ │ ├── response │ │ └── BaseResponse.java │ │ ├── shardingjdbc │ │ └── SingleKeyModuloTableShardingAlgorithm.java │ │ ├── spring │ │ └── AppSpringContext.java │ │ └── utils │ │ ├── ApiParamCheckUtil.java │ │ ├── CSVUtil.java │ │ ├── ClassUtils.java │ │ ├── ClientBuilder.java │ │ ├── DataExportWebUtils.java │ │ ├── DateTool.java │ │ ├── DateUtil.java │ │ ├── DateUtils.java │ │ ├── ExcelUtils.java │ │ ├── FTPUtil.java │ │ ├── FastJSONHelper.java │ │ ├── HttpClientUtil.java │ │ ├── JacksonMapper.java │ │ ├── JedisUtil.java │ │ ├── MathUtils.java │ │ ├── Md5Util.java │ │ ├── NamedThreadFactory.java │ │ ├── RedisLockUtil.java │ │ ├── ReflectionUtils.java │ │ ├── RespPackUtil.java │ │ ├── RetryHelper.java │ │ ├── RetryWrapper.java │ │ ├── SFTPUtil.java │ │ ├── ThreadPoolManager.java │ │ ├── Timeutils.java │ │ └── XmlUtil.java └── resources │ ├── META-INF │ └── spring │ │ ├── dubbo-gateway-customer.xml │ │ ├── dubbo-item-provider.xml │ │ ├── dubbo-order-provider.xml │ │ ├── dubbo-pk-customer.xml │ │ ├── dubbo-refund-provider.xml │ │ ├── inside-common-customer.xml │ │ └── manage-common-customer.xml │ ├── config │ ├── MyBatis-Configuration.xml │ └── redis_config.xml │ └── trade-core-spring │ ├── applicationContext-dubbo.xml │ ├── applicationContext-rpc.xml │ ├── applicationContext-trade-dao.xml │ ├── applicationContext-trade-datasource.xml │ └── applicationContext-trade.xml ├── profiles └── sit │ └── logback.xml └── test ├── java └── com │ └── liu │ └── sharding │ └── service │ ├── BaseServiceTest.java │ └── TestWriteShardingData.java └── resources ├── conf ├── MyBatis-Configuration.xml ├── applicationContext-sharding-dao.xml ├── applicationContext-sharding-datasource.xml ├── applicationContext-sharding.xml └── db.properties └── sqlMaps ├── TOuInfoMapper.xml └── TUserMapper.xml /READ.ME: -------------------------------------------------------------------------------- 1 | kafka设计原理:http://blog.csdn.net/suifeng3051/article/details/48053965 -------------------------------------------------------------------------------- /src/main/java/com/liu/Constants.java: -------------------------------------------------------------------------------- 1 | package com.liu; 2 | 3 | public class Constants { 4 | 5 | /**常量byte类型1**/ 6 | public static final byte CONSTANT_ONE_BYTE = 1; 7 | /**常量byte类型0 **/ 8 | public static final byte CONSTANT_ZERO_BYTE = 0; 9 | /**常量int类型1**/ 10 | public static final int CONSTANT_ONE_INT = 1; 11 | /**常量int类型0 **/ 12 | public static final int CONSTANT_ZERO_INT = 0; 13 | /** 常量字符串类型1 **/ 14 | public static final String CONSTANT_ONE_STR = "1"; 15 | 16 | public static final int CONSTANT_TEN_INT = 10; 17 | /**缓存过期时间一个月**/ 18 | public final static int REDIS_ONEMONTH = 2592000;//60*60*24*30 19 | /**缓存过期时间一天**/ 20 | public final static int REDIS_ONEDAY = 86400;//60*60*24 21 | /**缓存过期时间半天**/ 22 | public final static int REDIS_HALFDAY = 43200;//60*60*12 23 | /**缓存过期时间十天**/ 24 | public final static int REDIS_TENDAY = 864000;//60*60*24*10 25 | /**缓存过期时间十分钟**/ 26 | public final static int REDIS_TENMINUTE = 600;//60*10 27 | /**过期时间为一周**/ 28 | public static final int REDIS_ONEWEEK = 604800; 29 | /**缓存过期时间三小时**/ 30 | public final static int REDIS_THREEHOUR = 10800;//3*60*60 31 | /**缓存过期时间一小时**/ 32 | public final static int REDIS_ONEHOUR = 3600;//60*60 33 | /**缓存过期时间半小时**/ 34 | public final static int REDIS_HALFHOUR = 1800;//60*30 35 | /**缓存过期时间半分钟**/ 36 | public final static int REDIS_HALFMINUTE = 30; 37 | /**缓存过期时间90秒**/ 38 | public final static int REDIS_NINETY = 90; 39 | /**空字符串**/ 40 | public final static String CONSTANT_EMPTY_STR = ""; 41 | /**时间一天**/ 42 | public final static int CONSTANT_ONEDAY_SECOND = 86400;//60*60*24 43 | /**半小时毫秒数**/ 44 | public final static int HALFHOUR_MILLISECOND = 1800000; 45 | /**一个月的毫秒数**/ 46 | public final static long ONEMONTH_MILLISECOND = 2592000000L;//60*60*24*30*1000 47 | /** 常量30秒 **/ 48 | public static final int CONSTANT_THIRTY_SECOND = 30000; 49 | /**响应名称**/ 50 | public static final String RESPONSE_NAME = "result_code"; 51 | /**响应描述**/ 52 | public static final String RESPONSE_DESCR = "result_descr"; 53 | /**响应记录编码**/ 54 | public static final String RESPONSE_RECORDID = "result_recordId"; 55 | /**响应记录内容**/ 56 | public static final String RESPONSE_CONTENT = "result_content"; 57 | /** 常量字符串类型1 **/ 58 | public static final String CONSTANT_ZERO_STR = "0"; 59 | 60 | public static final String CONSUME_HANDLER = "HANDLER"; 61 | /**品类、sku分隔符**/ 62 | public static final String CAT_SKU_SPLIT = ","; 63 | /**请求头appid**/ 64 | public static final String AUTH_TOKEN = "CMMS_APPID"; 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/liu/code/BaseApiCode.java: -------------------------------------------------------------------------------- 1 | package com.liu.code; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | public class BaseApiCode { 9 | 10 | public static final Map enMsgMap = new HashMap(300); 11 | 12 | public static final Map zhMsgMap = new HashMap(300); 13 | 14 | public static List ignoreResultCodeList = new ArrayList(10); 15 | 16 | public static List retryResultCodeList = new ArrayList(10); 17 | 18 | /**操作成功**/ 19 | public static final String OPERATE_SUCCESS = "200"; 20 | /**操作失败**/ 21 | public static final String OPERATE_FAIL = "99"; 22 | /**操作超时**/ 23 | public static final String OPERATE_TIMEOUT = "98"; 24 | /**参数无效**/ 25 | public static final String OPERATE_PARAM_INVALID = "97"; 26 | /**操作无效**/ 27 | public static final String OPERATE_INVALID = "96"; 28 | /**部分成功**/ 29 | public static final String OPERATE_SOME_SUCCESS = "95"; 30 | /**相关系统异常**/ 31 | public static final String OPERATE_PARTNER_FAIL = "94"; 32 | /**平台异常**/ 33 | public static final String OPERATE_PLATFORM_FAIL = "93"; 34 | /**系统异常**/ 35 | public static final String OPERATE_SYSTEM_FAIL = "92"; 36 | /**操作正在处理中**/ 37 | public static final String OPERATE_PROCESSING = "91"; 38 | 39 | public static String getEnMsg(String errorCode){ 40 | return enMsgMap.get(errorCode); 41 | } 42 | 43 | public static String getZhMsg(String errorCode){ 44 | return zhMsgMap.get(errorCode); 45 | } 46 | 47 | static{ 48 | CardApiCode.initResponseCode(); 49 | 50 | enMsgMap.put(OPERATE_SUCCESS, "base.operate-success"); 51 | zhMsgMap.put(OPERATE_SUCCESS, "操作成功"); 52 | enMsgMap.put(OPERATE_FAIL, "base.operate-fail"); 53 | zhMsgMap.put(OPERATE_FAIL, "操作失败,建议刷新页面检查数据后再操作"); 54 | enMsgMap.put(OPERATE_TIMEOUT, "base.operate-timeout"); 55 | zhMsgMap.put(OPERATE_TIMEOUT, "操作超时,建议稍等一会再操作"); 56 | enMsgMap.put(OPERATE_PARAM_INVALID, "base.request-parameter-invalid"); 57 | zhMsgMap.put(OPERATE_PARAM_INVALID, "请求参数不合法"); 58 | enMsgMap.put(OPERATE_INVALID, "base.operate-invalid"); 59 | zhMsgMap.put(OPERATE_INVALID, "操作无效,建议刷新页面检查数据后再操作"); 60 | enMsgMap.put(OPERATE_SOME_SUCCESS, "base.operate-some-success"); 61 | zhMsgMap.put(OPERATE_SOME_SUCCESS, "调用部分成功"); 62 | enMsgMap.put(OPERATE_PARTNER_FAIL, "base.operate-partner-fail"); 63 | zhMsgMap.put(OPERATE_PARTNER_FAIL, "周边系统调用异常"); 64 | enMsgMap.put(OPERATE_PLATFORM_FAIL, "base.operate-platform-fail"); 65 | zhMsgMap.put(OPERATE_PLATFORM_FAIL, "平台调用异常"); 66 | enMsgMap.put(OPERATE_SYSTEM_FAIL, "base.operate-system-error"); 67 | zhMsgMap.put(OPERATE_SYSTEM_FAIL, "糟糕,系统卡壳了,请联系系统管理员"); 68 | enMsgMap.put(OPERATE_PROCESSING, "base.operate-processing"); 69 | zhMsgMap.put(OPERATE_PROCESSING, "操作正在处理中"); 70 | ignoreResultCodeList.add(BaseApiCode.OPERATE_INVALID); 71 | retryResultCodeList.add(BaseApiCode.OPERATE_TIMEOUT); 72 | retryResultCodeList.add(BaseApiCode.OPERATE_PROCESSING); 73 | retryResultCodeList.add(BaseApiCode.OPERATE_PARTNER_FAIL); 74 | retryResultCodeList.add(BaseApiCode.OPERATE_FAIL); 75 | retryResultCodeList.add(BaseApiCode.OPERATE_SYSTEM_FAIL); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/liu/code/CardApiCode.java: -------------------------------------------------------------------------------- 1 | package com.liu.code; 2 | 3 | import java.util.Map; 4 | 5 | public class CardApiCode extends BaseApiCode { 6 | 7 | /**券号不存在**/ 8 | public static final String CODE_NOT_EXIST = "1001"; 9 | /**cardId不存在**/ 10 | public static final String CARD_ID_NOT_EXIST = "1002"; 11 | /**领券次数超过限制**/ 12 | public static final String CARD_COUNT_LIMIT = "1003"; 13 | /**优惠券已过期**/ 14 | public static final String CARD_TIME_LIMIT = "1004"; 15 | /**优惠券已被领完**/ 16 | public static final String CARD_AMOUNT_LIMIT = "1005"; 17 | /**优惠券已核销**/ 18 | public static final String CARD_CONSUMED = "1006"; 19 | /**该券已绑定过用户**/ 20 | public static final String CARD_BINDED = "1007"; 21 | /**订单金额不满足最小优惠金额**/ 22 | public static final String CARD_MONEY_NOT_ALLOW = "1008"; 23 | /**当前优惠券已达到使用上限**/ 24 | public static final String CARD_ID_TIMLI = "1009"; 25 | /**当前优惠券已达到单用户使用上限**/ 26 | public static final String CARD_ID_LIMIT_PER_USER = "1010"; 27 | /**当前优惠券没有可赠送的礼品**/ 28 | public static final String CARD_NO_GIFT = "1011"; 29 | /**未知的优惠券类型**/ 30 | public static final String UNKNOW_CARD_TYPE = "1012"; 31 | /**没有选中的礼品**/ 32 | public static final String CARD_GIFT_EMPTY = "1013"; 33 | /**订单金额不满足优惠券类型**/ 34 | public static final String ORDER_MONEY_NOT_SATISFY = "1014"; 35 | /**优惠券活动还未开始**/ 36 | public static final String CARD_TIME_NOT_START = "1015"; 37 | 38 | 39 | public static void initResponseCode() { 40 | Map errorMsgMap = BaseApiCode.zhMsgMap; 41 | errorMsgMap.put(CARD_ID_NOT_EXIST, "cardId不存在"); 42 | errorMsgMap.put(CODE_NOT_EXIST, "券号code不存在"); 43 | errorMsgMap.put(CARD_COUNT_LIMIT, "领券次数超过限制"); 44 | errorMsgMap.put(CARD_TIME_LIMIT, "优惠券已过期"); 45 | errorMsgMap.put(CARD_AMOUNT_LIMIT, "优惠券已被领完"); 46 | errorMsgMap.put(CARD_CONSUMED, "优惠券已核销"); 47 | errorMsgMap.put(CARD_BINDED, "该券已绑定过用户"); 48 | errorMsgMap.put(CARD_MONEY_NOT_ALLOW, "订单金额不满足最小优惠金额"); 49 | errorMsgMap.put(CARD_ID_TIMLI, "当前优惠券已达到使用上限"); 50 | errorMsgMap.put(CARD_ID_LIMIT_PER_USER, "当前优惠券已达到单用户使用上限"); 51 | errorMsgMap.put(CARD_NO_GIFT, "当前优惠券没有可赠送的礼品"); 52 | errorMsgMap.put(UNKNOW_CARD_TYPE, "未知的优惠券类型"); 53 | errorMsgMap.put(CARD_GIFT_EMPTY, "没有选中的礼品"); 54 | errorMsgMap.put(ORDER_MONEY_NOT_SATISFY, "订单金额不满足优惠券类型"); 55 | errorMsgMap.put(CARD_TIME_NOT_START, "优惠券活动还未开始"); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/liu/code/FileUploadApiCode.java: -------------------------------------------------------------------------------- 1 | package com.liu.code; 2 | 3 | import java.util.Map; 4 | 5 | public class FileUploadApiCode { 6 | 7 | /** 8 | * 超出允许上传的最大文件大小 9 | */ 10 | public static final String EXCEED_MAX_UPLOAD_SIZE = "801"; 11 | /** 12 | * 上传文件夹为空 13 | */ 14 | public static final String UPLOAD_DIR_PATH_IS_NULL = "802"; 15 | /** 16 | * 非法状态 17 | */ 18 | public static final String ILLEGAL_STATE = "803"; 19 | /** 20 | * IO异常 21 | */ 22 | public static final String IO_EXCEPTION = "804"; 23 | /** 24 | * 文件格式不对 25 | */ 26 | public static final String INVALID_FORMAT = "805"; 27 | /** 28 | * excel上传数据条目数过多 29 | */ 30 | public static final String EXCEL_MAX_NUMBER = "806"; 31 | 32 | public static void initResponseCode() { 33 | Map enMsgMap = BaseApiCode.enMsgMap; 34 | Map zhMsgMap = BaseApiCode.zhMsgMap; 35 | 36 | enMsgMap.put(EXCEED_MAX_UPLOAD_SIZE, 37 | "fileupload.exceed-max-upload-size"); 38 | zhMsgMap.put(EXCEED_MAX_UPLOAD_SIZE, "上传文件太大,请保证文件小于30M"); 39 | enMsgMap.put(UPLOAD_DIR_PATH_IS_NULL, 40 | "fileupload.upload-dir-path-is-null"); 41 | zhMsgMap.put(UPLOAD_DIR_PATH_IS_NULL, "上传文件路径为空"); 42 | 43 | enMsgMap.put(ILLEGAL_STATE, "fileupload.illegal-state"); 44 | zhMsgMap.put(ILLEGAL_STATE, "上传文件出现异常,非法的状态"); 45 | enMsgMap.put(IO_EXCEPTION, "fileupload.io-exception"); 46 | zhMsgMap.put(IO_EXCEPTION, "上传文件出现IO异常"); 47 | enMsgMap.put(INVALID_FORMAT, "fileupload.invalid-format"); 48 | zhMsgMap.put(INVALID_FORMAT, "上传文件格式不对"); 49 | enMsgMap.put(EXCEL_MAX_NUMBER, "import.excel-import-max-number"); 50 | zhMsgMap.put(EXCEL_MAX_NUMBER, "导入的excel数据条数过多,请分批次导入。"); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/liu/core/AppSpringContext.java: -------------------------------------------------------------------------------- 1 | package com.liu.core; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | import org.springframework.util.Assert; 7 | 8 | public class AppSpringContext implements ApplicationContextAware{ 9 | 10 | private static ApplicationContext applicationContext; 11 | 12 | @Override 13 | public void setApplicationContext(ApplicationContext appContext) 14 | throws BeansException { 15 | AppSpringContext.applicationContext = appContext; 16 | } 17 | 18 | /** 19 | * @return ApplicationContext 20 | */ 21 | public static ApplicationContext getApplicationContext() { 22 | return applicationContext; 23 | } 24 | /** 25 | * 获取bean对象 26 | * @param clazz 27 | * @return 28 | */ 29 | public static T getBean(Class clazz){ 30 | Assert.notNull(applicationContext, "Application Context not initialize"); 31 | return applicationContext.getBean(clazz); 32 | } 33 | /** 34 | * 获取 bean 对象 35 | * @param beanName 36 | * @param clazz 37 | * @return 38 | */ 39 | public static T getBean(String beanName,Class clazz){ 40 | Assert.notNull(applicationContext, "Application Context not initialize"); 41 | return applicationContext.getBean(beanName, clazz); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/liu/core/JedisCallback.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright © 1968-2014 美的集团股份有限公司 3 | * @FileName: JedisCallback.java 4 | * @Package com.midea.trade.core.impl.core.jedis 5 | * @Description: 6 | * @author 汪海霖 wanghl15@midea.com.cn 7 | * @date 2014-9-2 下午2:18:46 8 | * @version V0.0.1 9 | */ 10 | package com.liu.core; 11 | 12 | import redis.clients.jedis.ShardedJedis; 13 | 14 | 15 | /** 16 | * @ClassName: JedisCallback 17 | * @Description: 18 | * @author 汪海霖 wanghl15@midea.com.cn 19 | * @date 2014-9-2 下午2:18:46 20 | */ 21 | public interface JedisCallback { 22 | 23 | public T invoke(ShardedJedis jedis); 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/liu/core/PipelineCallback.java: -------------------------------------------------------------------------------- 1 | package com.liu.core; 2 | 3 | import redis.clients.jedis.ShardedJedisPipeline; 4 | /** 5 | * redis Pipeline 操作抽象类 6 | * @ClassName: PipelineCallback 7 | * @Description: 8 | * @author 汪海霖 wanghl15@midea.com.cn 9 | * @date 2014-5-16 下午5:12:35 10 | * 11 | */ 12 | public interface PipelineCallback { 13 | /** 14 | * 管道操作 15 | * @Title: invokePipeline 16 | * @Description: 17 | * @param @param pipeline 18 | * @return void 19 | * @throws 20 | */ 21 | public void invokePipeline(ShardedJedisPipeline pipeline); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/liu/core/ServiceWrapper.java: -------------------------------------------------------------------------------- 1 | package com.liu.core; 2 | 3 | import com.liu.response.BaseResponse; 4 | /** 5 | * 6 | * @ClassName: ServiceWrapper 7 | * @Description: 服务包装类 8 | * @author 汪海霖 wanghl15@midea.com.cn 9 | * @date 2015-4-23 下午1:57:12 10 | */ 11 | 12 | public abstract class ServiceWrapper { 13 | 14 | //调用服务 15 | public abstract String invokeService(); 16 | 17 | //是否监控失败请求 18 | public boolean isMonitorFail(){ 19 | return true; 20 | } 21 | 22 | //是否监控成功请求 23 | public boolean isMonitorSuccess(){ 24 | return false; 25 | } 26 | 27 | //超时时间 28 | public int timeout(){ 29 | return 500; 30 | } 31 | 32 | //是否通知调用失败 33 | public boolean isNoticeInvokeFail(BaseResponse response){ 34 | return false; 35 | } 36 | 37 | //获取请求traceId 38 | public String getTraceId(){ 39 | return null; 40 | } 41 | 42 | //发送变更通知 43 | public Boolean sendChangeNotify(){ 44 | return null; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/liu/core/dao/TOuInfoMapper.java: -------------------------------------------------------------------------------- 1 | package com.liu.core.dao; 2 | 3 | import com.liu.core.dao.annotation.IRepository; 4 | import com.liu.core.entity.TOuInfo; 5 | import com.liu.core.entity.TOuInfoExample; 6 | import java.util.List; 7 | import org.apache.ibatis.annotations.Param; 8 | 9 | @IRepository 10 | public interface TOuInfoMapper { 11 | int countByExample(TOuInfoExample example); 12 | 13 | int deleteByExample(TOuInfoExample example); 14 | 15 | int deleteByPrimaryKey(Long id); 16 | 17 | int insert(TOuInfo record); 18 | 19 | int insertSelective(TOuInfo record); 20 | 21 | List selectByExample(TOuInfoExample example); 22 | 23 | TOuInfo selectByPrimaryKey(Long id); 24 | 25 | int updateByExampleSelective(@Param("record") TOuInfo record, @Param("example") TOuInfoExample example); 26 | 27 | int updateByExample(@Param("record") TOuInfo record, @Param("example") TOuInfoExample example); 28 | 29 | int updateByPrimaryKeySelective(TOuInfo record); 30 | 31 | int updateByPrimaryKey(TOuInfo record); 32 | } -------------------------------------------------------------------------------- /src/main/java/com/liu/core/dao/TUserMapper.java: -------------------------------------------------------------------------------- 1 | package com.liu.core.dao; 2 | 3 | import com.liu.core.dao.annotation.IRepository; 4 | import com.liu.core.entity.TUser; 5 | import com.liu.core.entity.TUserExample; 6 | import java.util.List; 7 | import org.apache.ibatis.annotations.Param; 8 | 9 | @IRepository 10 | public interface TUserMapper { 11 | int countByExample(TUserExample example); 12 | 13 | int deleteByExample(TUserExample example); 14 | 15 | int deleteByPrimaryKey(Long id); 16 | 17 | int insert(TUser record); 18 | 19 | int insertSelective(TUser record); 20 | 21 | List selectByExample(TUserExample example); 22 | 23 | TUser selectByPrimaryKey(Long id); 24 | 25 | int updateByExampleSelective(@Param("record") TUser record, @Param("example") TUserExample example); 26 | 27 | int updateByExample(@Param("record") TUser record, @Param("example") TUserExample example); 28 | 29 | int updateByPrimaryKeySelective(TUser record); 30 | 31 | int updateByPrimaryKey(TUser record); 32 | } -------------------------------------------------------------------------------- /src/main/java/com/liu/core/dao/annotation/IRepository.java: -------------------------------------------------------------------------------- 1 | package com.liu.core.dao.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | import org.springframework.stereotype.Component; 10 | 11 | /** 12 | * 标识MyBatis的DAO,方便{@link org.mybatis.spring.mapper.MapperScannerConfigurer}的扫描。 13 | * 14 | */ 15 | @Retention(RetentionPolicy.RUNTIME) 16 | @Target(ElementType.TYPE) 17 | @Documented 18 | @Component 19 | public @interface IRepository { 20 | String value() default ""; 21 | } -------------------------------------------------------------------------------- /src/main/java/com/liu/core/entity/TOuInfo.java: -------------------------------------------------------------------------------- 1 | package com.liu.core.entity; 2 | 3 | import java.util.Date; 4 | 5 | public class TOuInfo { 6 | private Long id; 7 | 8 | private Integer ouId; 9 | 10 | private String ouName; 11 | 12 | private String ouAddress; 13 | 14 | private Date cretaeTime; 15 | 16 | private Date updateTime; 17 | 18 | public Long getId() { 19 | return id; 20 | } 21 | 22 | public void setId(Long id) { 23 | this.id = id; 24 | } 25 | 26 | public Integer getOuId() { 27 | return ouId; 28 | } 29 | 30 | public void setOuId(Integer ouId) { 31 | this.ouId = ouId; 32 | } 33 | 34 | public String getOuName() { 35 | return ouName; 36 | } 37 | 38 | public void setOuName(String ouName) { 39 | this.ouName = ouName == null ? null : ouName.trim(); 40 | } 41 | 42 | public String getOuAddress() { 43 | return ouAddress; 44 | } 45 | 46 | public void setOuAddress(String ouAddress) { 47 | this.ouAddress = ouAddress == null ? null : ouAddress.trim(); 48 | } 49 | 50 | public Date getCretaeTime() { 51 | return cretaeTime; 52 | } 53 | 54 | public void setCretaeTime(Date cretaeTime) { 55 | this.cretaeTime = cretaeTime; 56 | } 57 | 58 | public Date getUpdateTime() { 59 | return updateTime; 60 | } 61 | 62 | public void setUpdateTime(Date updateTime) { 63 | this.updateTime = updateTime; 64 | } 65 | } -------------------------------------------------------------------------------- /src/main/java/com/liu/core/entity/TUser.java: -------------------------------------------------------------------------------- 1 | package com.liu.core.entity; 2 | 3 | import java.util.Date; 4 | 5 | public class TUser { 6 | private Long id; 7 | 8 | private Integer ouId; 9 | 10 | private String name; 11 | 12 | private Integer age; 13 | 14 | private String position; 15 | 16 | private Date createTime; 17 | 18 | private Date updateTime; 19 | 20 | public Long getId() { 21 | return id; 22 | } 23 | 24 | public void setId(Long id) { 25 | this.id = id; 26 | } 27 | 28 | public Integer getOuId() { 29 | return ouId; 30 | } 31 | 32 | public void setOuId(Integer ouId) { 33 | this.ouId = ouId; 34 | } 35 | 36 | public String getName() { 37 | return name; 38 | } 39 | 40 | public void setName(String name) { 41 | this.name = name == null ? null : name.trim(); 42 | } 43 | 44 | public Integer getAge() { 45 | return age; 46 | } 47 | 48 | public void setAge(Integer age) { 49 | this.age = age; 50 | } 51 | 52 | public String getPosition() { 53 | return position; 54 | } 55 | 56 | public void setPosition(String position) { 57 | this.position = position == null ? null : position.trim(); 58 | } 59 | 60 | public Date getCreateTime() { 61 | return createTime; 62 | } 63 | 64 | public void setCreateTime(Date createTime) { 65 | this.createTime = createTime; 66 | } 67 | 68 | public Date getUpdateTime() { 69 | return updateTime; 70 | } 71 | 72 | public void setUpdateTime(Date updateTime) { 73 | this.updateTime = updateTime; 74 | } 75 | } -------------------------------------------------------------------------------- /src/main/java/com/liu/custom/annotation/FruitColor.java: -------------------------------------------------------------------------------- 1 | package com.liu.custom.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target(ElementType.FIELD) 11 | @Documented 12 | public @interface FruitColor { 13 | 14 | /** 15 | * 颜色枚举 16 | * @author liuzhihong 17 | * 18 | */ 19 | public enum Color{RED,GREEN,BLUE}; 20 | 21 | /** 22 | * 颜色属性 23 | * @return 24 | */ 25 | Color fruitColor() default Color.RED; 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/liu/custom/annotation/FruitName.java: -------------------------------------------------------------------------------- 1 | package com.liu.custom.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target(ElementType.FIELD) 11 | @Documented 12 | public @interface FruitName { 13 | 14 | public String value() default ""; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/liu/custom/annotation/FruitProvider.java: -------------------------------------------------------------------------------- 1 | package com.liu.custom.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * 水果供应商 11 | * @author liuzhihong 12 | * 13 | */ 14 | @Retention(RetentionPolicy.RUNTIME) 15 | @Target(ElementType.FIELD) 16 | @Documented 17 | public @interface FruitProvider { 18 | 19 | /**供应商ID*/ 20 | public int id() default -1; 21 | 22 | /**供应商名称*/ 23 | String name() default ""; 24 | 25 | /**供应商地址*/ 26 | String address() default ""; 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/liu/custom/annotation/use/Apple.java: -------------------------------------------------------------------------------- 1 | package com.liu.custom.annotation.use; 2 | 3 | import com.liu.custom.annotation.FruitColor; 4 | import com.liu.custom.annotation.FruitColor.Color; 5 | import com.liu.custom.annotation.FruitName; 6 | import com.liu.custom.annotation.FruitProvider; 7 | 8 | /** 9 | * 10 | * @author liuzhihong 11 | * 12 | */ 13 | public class Apple { 14 | 15 | @FruitName("Apple") 16 | private String appleName; 17 | 18 | @FruitColor(fruitColor=Color.GREEN) 19 | private String appleColor; 20 | 21 | @FruitProvider(id=2,name="midea",address="顺德") 22 | private String appleProvider; 23 | 24 | public String getAppleName() { 25 | return appleName; 26 | } 27 | 28 | public void setAppleName(String appleName) { 29 | this.appleName = appleName; 30 | } 31 | 32 | public String getAppleColor() { 33 | return appleColor; 34 | } 35 | 36 | public void setAppleColor(String appleColor) { 37 | this.appleColor = appleColor; 38 | } 39 | 40 | public String getAppleProvider() { 41 | return appleProvider; 42 | } 43 | 44 | public void setAppleProvider(String appleProvider) { 45 | this.appleProvider = appleProvider; 46 | } 47 | 48 | public void display(){ 49 | System.out.println("水果的名字是: "+appleName); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/liu/custom/annotation/use/FruitMain.java: -------------------------------------------------------------------------------- 1 | package com.liu.custom.annotation.use; 2 | 3 | public class FruitMain { 4 | 5 | public static void main(String[] args) { 6 | 7 | FruitProcessUtil.getFruitInfo(Apple.class); 8 | 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/liu/custom/annotation/use/FruitProcessUtil.java: -------------------------------------------------------------------------------- 1 | package com.liu.custom.annotation.use; 2 | 3 | import java.lang.reflect.Field; 4 | 5 | import com.liu.custom.annotation.FruitName; 6 | 7 | public class FruitProcessUtil { 8 | 9 | public static void getFruitInfo(Class clazz){ 10 | 11 | String strName = "水果名称为: "; 12 | String strColor = "水果颜色为: "; 13 | String strProvider = "水果供应商为: "; 14 | 15 | Field[] fields = clazz.getDeclaredFields(); 16 | 17 | for(Field fl : fields){ 18 | if(fl.isAnnotationPresent(FruitName.class)){ 19 | FruitName fruitName = fl.getAnnotation(FruitName.class); 20 | strName = strName+fruitName.value(); 21 | System.out.println(strName); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/liu/elasticsearch/Blog.java: -------------------------------------------------------------------------------- 1 | package com.liu.elasticsearch; 2 | 3 | import java.util.Date; 4 | 5 | import lombok.Data; 6 | 7 | @Data 8 | public class Blog { 9 | 10 | private Integer id; 11 | private String title; 12 | private Date posttime; 13 | private String content; 14 | 15 | public Blog() { 16 | } 17 | 18 | public Blog(Integer id, String title, Date posttime, String content) { 19 | this.id = id; 20 | this.title = title; 21 | this.posttime = posttime; 22 | this.content = content; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/liu/elasticsearch/DataFactory.java: -------------------------------------------------------------------------------- 1 | package com.liu.elasticsearch; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import com.liu.utils.DateTool; 7 | 8 | public class DataFactory { 9 | 10 | public static DataFactory dataFactory = new DataFactory(); 11 | 12 | private DataFactory() { 13 | } 14 | 15 | public DataFactory getInstance() { 16 | return dataFactory; 17 | } 18 | 19 | public static List getInitJsonData() { 20 | List list = new ArrayList(); 21 | String data1 = JsonUtils.modelToJson(new Blog(1, "git简介", DateTool.stringToDate("2016-06-19"), "SVN与Git最主要的区别...")); 22 | String data2 = JsonUtils.modelToJson(new Blog(2, "Java中泛型的介绍与简单使用", DateTool.stringToDate("2016-07-19"), "学习目标 掌握泛型的产生意义...")); 23 | String data3 = JsonUtils.modelToJson(new Blog(3, "SQL基本操作", DateTool.stringToDate("2017-01-08"), "基本操作:CRUD ...")); 24 | String data4 = JsonUtils.modelToJson(new Blog(4, "Hibernate框架基础", DateTool.stringToDate("2016-08-15"), "Hibernate框架基础...")); 25 | String data5 = JsonUtils.modelToJson(new Blog(5, "Shell基本知识", DateTool.stringToDate("2017-04-07"), "Shell是什么...")); 26 | list.add(data1); 27 | list.add(data2); 28 | list.add(data3); 29 | list.add(data4); 30 | list.add(data5); 31 | return list; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/liu/elasticsearch/ElasticSearchHandler.java: -------------------------------------------------------------------------------- 1 | package com.liu.elasticsearch; 2 | 3 | import java.util.List; 4 | 5 | import org.elasticsearch.action.index.IndexResponse; 6 | import org.elasticsearch.client.Client; 7 | 8 | import com.liu.utils.ClientBuilder; 9 | 10 | public class ElasticSearchHandler { 11 | 12 | public static void main(String[] args) { 13 | Client client = ClientBuilder.getJestClient(); 14 | List jsonData = DataFactory.getInitJsonData(); 15 | for(String str : jsonData){ 16 | IndexResponse response = client.prepareIndex("blog", "article").setSource(str).get(); 17 | if(response.isCreated()){ 18 | System.out.println("创建成功!"+response.getIndex()+":"+response.getType()); 19 | } 20 | } 21 | /*QueryBuilder queryBuilder = QueryBuilders.matchAllQuery(); 22 | SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article").setQuery(queryBuilder).execute().actionGet(); 23 | SearchHits searchHits = searchResponse.getHits(); 24 | Date start = DateTool.stringToDate("2017-03-01"); 25 | try { 26 | for(SearchHit hit : searchHits){ 27 | UpdateRequest updateRequest = new UpdateRequest(); 28 | updateRequest.index("blog"); 29 | updateRequest.type("article"); 30 | updateRequest.id(hit.getId()); 31 | updateRequest.doc(XContentFactory.jsonBuilder().startObject().field("marketTime", start).endObject()); 32 | UpdateResponse response = client.update(updateRequest).actionGet(); 33 | start = DateUtils.addDays(start, 1); 34 | } 35 | } catch (ElasticsearchException e) { 36 | // TODO Auto-generated catch block 37 | e.printStackTrace(); 38 | } catch (IOException e) { 39 | // TODO Auto-generated catch block 40 | e.printStackTrace(); 41 | } finally { 42 | client.close(); 43 | }*/ 44 | //删除索引 45 | //client.admin().indices().prepareDelete("blog").execute().actionGet(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/liu/elasticsearch/JsonUtils.java: -------------------------------------------------------------------------------- 1 | package com.liu.elasticsearch; 2 | 3 | import java.io.IOException; 4 | 5 | import org.elasticsearch.common.xcontent.XContentBuilder; 6 | import org.elasticsearch.common.xcontent.XContentFactory; 7 | 8 | public class JsonUtils { 9 | 10 | public static String modelToJson(Blog blog){ 11 | String jsonData = null; 12 | try { 13 | XContentBuilder builder = XContentFactory.jsonBuilder(); 14 | builder.startObject().field("id", blog.getId()).field("title", blog.getTitle()) 15 | .field("posttime", blog.getPosttime()).field("content", blog.getContent()).endObject(); 16 | 17 | jsonData = builder.string(); 18 | } catch (IOException e) { 19 | // TODO Auto-generated catch block 20 | e.printStackTrace(); 21 | } 22 | 23 | return jsonData; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/liu/elasticsearch/search/BlogParam.java: -------------------------------------------------------------------------------- 1 | package com.liu.elasticsearch.search; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import lombok.Data; 7 | 8 | @Data 9 | public class BlogParam { 10 | 11 | private Integer id;//主键id 12 | private List ids; 13 | private String title;//标题 14 | private Date posttime;//发版时间 15 | private Date marketTime;//上市时间 16 | private String content;//简介 17 | private Integer from; 18 | private Integer size; 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/liu/elasticsearch/search/BlogService.java: -------------------------------------------------------------------------------- 1 | package com.liu.elasticsearch.search; 2 | 3 | import java.util.List; 4 | 5 | import com.liu.elasticsearch.Blog; 6 | 7 | public interface BlogService { 8 | 9 | List fetchBlogInfoFromSearch(BlogParam para); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/liu/elasticsearch/search/BlogServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.liu.elasticsearch.search; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Date; 5 | import java.util.List; 6 | 7 | import org.apache.commons.collections.CollectionUtils; 8 | import org.elasticsearch.action.search.SearchRequestBuilder; 9 | import org.elasticsearch.action.search.SearchResponse; 10 | import org.elasticsearch.action.search.SearchType; 11 | import org.elasticsearch.client.Client; 12 | import org.elasticsearch.index.query.FilterBuilder; 13 | import org.elasticsearch.index.query.QueryBuilder; 14 | import org.elasticsearch.index.query.QueryBuilders; 15 | import org.elasticsearch.search.SearchHit; 16 | import org.elasticsearch.search.SearchHits; 17 | import org.elasticsearch.search.sort.SortOrder; 18 | 19 | import com.liu.elasticsearch.Blog; 20 | import com.liu.utils.ClientBuilder; 21 | import com.liu.utils.DateUtil; 22 | 23 | public class BlogServiceImpl implements BlogService { 24 | 25 | @Override 26 | public List fetchBlogInfoFromSearch(BlogParam para) { 27 | if(para == null){ 28 | return null; 29 | } 30 | List list = new ArrayList(); 31 | Client client = ClientBuilder.getJestClient(); 32 | QueryBuilder queryDsl = QueryBuilders.constantScoreQuery(ElasticSearchQueryUtils.blogQueryWapper(para)); 33 | FilterBuilder filter = ElasticSearchQueryUtils.blogFilterWapper(para); 34 | SearchRequestBuilder searchRequestBuilder = client.prepareSearch("blog"); 35 | // 设置查询索引类型 36 | searchRequestBuilder.setTypes("article"); 37 | // 设置查询类型 38 | // 1.SearchType.DFS_QUERY_THEN_FETCH = 精确查询 39 | // 2.SearchType.SCAN = 扫描查询,无序 40 | // 3.SearchType.COUNT = 不设置的话,这个为默认值,还有的自己去试试吧 41 | searchRequestBuilder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH); 42 | searchRequestBuilder.addSort("posttime", SortOrder.DESC); 43 | searchRequestBuilder.setQuery(queryDsl); 44 | searchRequestBuilder.setPostFilter(filter); 45 | setShardRouting(searchRequestBuilder, para, "sys_user"); 46 | // 创建查询索引 47 | //int startRow = pageIndex * pageSize; 48 | searchRequestBuilder.setFrom(para.getFrom()); 49 | searchRequestBuilder.setSize(para.getSize()); 50 | SearchResponse res = searchRequestBuilder.execute().actionGet(); 51 | SearchHits hits = res.getHits(); 52 | for (SearchHit hit : hits) { 53 | String json = hit.getSourceAsString(); 54 | System.out.println("从搜索引擎检索的数据为"+json); 55 | Blog blog = com.liu.utils.FastJSONHelper.deserialize(json, Blog.class); 56 | list.add(blog); 57 | } 58 | return list; 59 | } 60 | 61 | private void setShardRouting(SearchRequestBuilder searchRequestBuilder, BlogParam para, String string) { 62 | Date endTime = para.getMarketTime() != null ? para.getMarketTime() : new Date(); 63 | Date startTime = para.getPosttime() != null ? para.getPosttime() : DateUtil.addMonths(endTime, -3); 64 | Date start = DateUtil.getFirstDayOfTheMonth(startTime); 65 | Date end = DateUtil.getFirstDayOfTheMonth(endTime); 66 | List routeTable = new ArrayList(); 67 | for (Date i = start; i.compareTo(end) <= 0; i = DateUtil.addMonths(i, 1)) { 68 | routeTable.add(DateUtil.formatMonth(i)); 69 | } 70 | if (CollectionUtils.isNotEmpty(routeTable)) { 71 | searchRequestBuilder.setRouting(routeTable.toArray(new String[routeTable.size()])); 72 | } else { 73 | searchRequestBuilder.setRouting(DateUtil.formatMonth(start)); 74 | } 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/liu/elasticsearch/search/ElasticSearchQueryHandler.java: -------------------------------------------------------------------------------- 1 | package com.liu.elasticsearch.search; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import com.liu.elasticsearch.Blog; 7 | import com.liu.utils.DateTool; 8 | 9 | public class ElasticSearchQueryHandler { 10 | 11 | public static void main(String[] args) { 12 | BlogServiceImpl blogServiceImpl = new BlogServiceImpl(); 13 | BlogParam para = new BlogParam(); 14 | para.setFrom(0); 15 | para.setSize(4); 16 | /*List ids = new ArrayList(); 17 | ids.add(1); 18 | ids.add(3); 19 | para.setIds(ids);*/ 20 | para.setPosttime(DateTool.stringToDate("2016-06-19")); 21 | para.setMarketTime(DateTool.stringToDate("2017-03-20")); 22 | //para.setTitle("Shell基本知识"); 23 | para.setContent("Hibernate"); 24 | List list = blogServiceImpl.fetchBlogInfoFromSearch(para); 25 | //System.out.println(FastJsonHelper.serialize(list)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/liu/elasticsearch/search/ElasticSearchQueryUtils.java: -------------------------------------------------------------------------------- 1 | package com.liu.elasticsearch.search; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | import org.apache.commons.collections.CollectionUtils; 7 | import org.elasticsearch.index.query.AndFilterBuilder; 8 | import org.elasticsearch.index.query.BoolQueryBuilder; 9 | import org.elasticsearch.index.query.FilterBuilder; 10 | import org.elasticsearch.index.query.FilterBuilders; 11 | import org.elasticsearch.index.query.MatchQueryBuilder; 12 | import org.elasticsearch.index.query.QueryBuilder; 13 | import org.elasticsearch.index.query.QueryBuilders; 14 | import org.elasticsearch.index.query.RangeFilterBuilder; 15 | import org.elasticsearch.index.query.WildcardQueryBuilder; 16 | 17 | public class ElasticSearchQueryUtils { 18 | 19 | private static Pattern pattern = Pattern.compile("^[A-Za-z\\.]+$"); 20 | 21 | public static QueryBuilder blogQueryWapper(BlogParam request) { 22 | BoolQueryBuilder mustQueryBuilder=QueryBuilders.boolQuery(); 23 | 24 | if (request.getTitle()!= null) { 25 | MatchQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("title", request.getTitle()); 26 | mustQueryBuilder = mustQueryBuilder.must(matchPhraseQueryBuilder); 27 | } 28 | 29 | /*if (request.getPosttime() != null) { 30 | MatchQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("posttime", request.getPosttime()); 31 | mustQueryBuilder = mustQueryBuilder.must(matchPhraseQueryBuilder); 32 | }*/ 33 | if(request.getContent() !=null){ 34 | Matcher m = pattern.matcher(request.getContent()); 35 | if(m.find()){ 36 | //通配符查询 37 | WildcardQueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery("content", "*"+request.getContent().toLowerCase()+"*"); 38 | mustQueryBuilder = mustQueryBuilder.must(wildcardQueryBuilder); 39 | }else{ 40 | MatchQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("content",request.getContent()); 41 | mustQueryBuilder = mustQueryBuilder.must(matchPhraseQueryBuilder); 42 | } 43 | 44 | } 45 | return mustQueryBuilder; 46 | } 47 | 48 | public static FilterBuilder blogFilterWapper(BlogParam request) { 49 | AndFilterBuilder andFilterBuilder = FilterBuilders.andFilter(); 50 | 51 | if (request.getTitle() != null) { 52 | andFilterBuilder.add(FilterBuilders.termFilter("title", request.getTitle())); 53 | } 54 | 55 | if (request.getPosttime() != null || request.getMarketTime() != null) { 56 | RangeFilterBuilder rangeFilterBuilder=FilterBuilders.rangeFilter("posttime"); 57 | if (request.getPosttime() != null) { 58 | rangeFilterBuilder.gte(request.getPosttime().getTime()); 59 | } 60 | if (request.getMarketTime() != null) { 61 | rangeFilterBuilder.lte(request.getMarketTime().getTime()); 62 | } 63 | andFilterBuilder.add(rangeFilterBuilder); 64 | } 65 | 66 | if (request.getId() != null) { 67 | andFilterBuilder.add(FilterBuilders.termFilter("id", request.getId())); 68 | }else if(CollectionUtils.isNotEmpty(request.getIds())){ 69 | andFilterBuilder.add(FilterBuilders.inFilter("id", request.getIds().toArray())); 70 | } 71 | /*if (request.getContent() != null) { 72 | andFilterBuilder.add(FilterBuilders.termFilter("content", request.getContent())); 73 | }*/ 74 | /*if(request.getIsHaveMemo()!=null&&request.getIsHaveMemo()){ 75 | andFilterBuilder.add(FilterBuilders.orFilter(FilterBuilders.existsFilter("order.sellerMemo"), 76 | FilterBuilders.existsFilter("order.buyerMemo"))); 77 | } 78 | if(request.getIsHaveMemo()!=null&&(!request.getIsHaveMemo())){ 79 | andFilterBuilder.add(FilterBuilders.missingFilter(("order.sellerMemo"))); 80 | andFilterBuilder.add(FilterBuilders.missingFilter(("order.buyerMemo"))); 81 | } 82 | if(request.getStatus()!=null&&request.getStatus()==(byte)0){ 83 | andFilterBuilder.add(FilterBuilders.notFilter(FilterBuilders.termFilter("items.status",(byte)1))); 84 | }*/ 85 | return andFilterBuilder; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/liu/enums/MqSendType.java: -------------------------------------------------------------------------------- 1 | package com.liu.enums; 2 | 3 | /** 4 | * 5 | * @ClassName: MqSendType 6 | * @Description: MQ发送类型 7 | * @author 汪海霖 wanghl15@midea.com.cn 8 | * @date 2015-4-4 上午11:16:13 9 | */ 10 | public enum MqSendType { 11 | 12 | TRADE_GATEWAY_RCV("trade-gateway", "gatewayMsgRcvStatus", null),//接入结果回写 13 | PACKING_SELF_SEND("packing_order", "send", "pack"),//配货单发送安得 14 | PACKING_3W_SEND("packing_order_3w", "send", "3w"),//3W配货单发送 15 | TRADE_ACCESS_NOTIFY("trade-event-notify", "tradeAccess", "tAccess"),//订单接入 16 | TRADE_STATUS_NOTIFY("trade-event-notify", "tradeStatusChange", "tStatus"),//订单状态变更 17 | TRADE_CONTENT_NOTIFY("trade-event-notify", "tradeContentChange", "tContent"),//订单内容发送变更 18 | ORDERITEM_STATUS_NOTIFY("trade-event-notify", "orderItemStatusChange","iStatus"),//订单商品状态变更 19 | REFUND_ACCESS_NOTIFY("trade-event-notify", "refundAccess", "rAccess"),//售后申请单接入 20 | REFUND_STATUS_NOTIFY("trade-event-notify", "refundStatusChange", "rStatus"),//售后申请单状态变更 21 | REFUND_CONTENT_NOTIFY("trade-event-notify", "refundContentChange", "rContent"),//申请单内容发送变更 22 | REFUND_PAY_ACCESS_NOTIFY("trade-event-notify", "refundPayAccess", "rpAccess"),//退款单接入 23 | REFUND_PAY_STATUS_NOTIFY("trade-event-notify", "refundPayStatusChange", "rpStatus"),//退款单状态变更 24 | REFUND_PAY_CONTENT_NOTIFY("trade-event-notify", "refundPayContentChange", "rpContent"),//退款单内容发送变更 25 | SERVICE_FAIL_NOTICE("fault_reporter", "core_notice", "notice"),//异常预警 26 | JDS_TRADE_TRACES("trade-traces", "jdsTradeTrace", "trade_traces"),//全链路 正向 27 | IMS_ORDER_CREATE("ims_order", "imsOrderCreate", "imsOrder");//IMS销售单 28 | 29 | private String topic; 30 | 31 | private String tag; 32 | 33 | private String prefix; 34 | 35 | private MqSendType(String topic,String tag,String prefix){ 36 | this.topic = topic; 37 | this.tag = tag; 38 | this.prefix = prefix; 39 | } 40 | 41 | public String getPrefix() { 42 | return prefix; 43 | } 44 | 45 | public void setPrefix(String prefix) { 46 | this.prefix = prefix; 47 | } 48 | 49 | public String getTopic() { 50 | return topic; 51 | } 52 | 53 | public void setTopic(String topic) { 54 | this.topic = topic; 55 | } 56 | 57 | public String getTag() { 58 | return tag; 59 | } 60 | 61 | public void setTag(String tag) { 62 | this.tag = tag; 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/liu/exceptions/BaseException.java: -------------------------------------------------------------------------------- 1 | package com.liu.exceptions; 2 | 3 | /** 4 | * @ClassName: BaseException 5 | * @Description: 系统基本异常类 6 | * @author libin.chen@midea.com.cn 7 | * @date 2015年8月15日 下午4:36:03 8 | * 9 | */ 10 | public class BaseException extends MideaException { 11 | 12 | private static final long serialVersionUID = -5997285054839713700L; 13 | 14 | public static BaseException PARAM_INVALID = new BaseException(97, "PARAM_INVALID", "参数无效"); 15 | 16 | public static BaseException OPERATE_TIMEOUT = new BaseException(96, "OPERATE_TIMEOUT", "操作超时"); 17 | 18 | public static BaseException UNKNOWN_SYSTEM_FAIL = new BaseException(95, "UNKNOWN_SYSTEM_FAIL", "亲,系统出现异常,请联系管理员!"); 19 | 20 | protected BaseException(Integer status, String defineCode, String chnDesc) { 21 | super(status, defineCode, chnDesc); 22 | } 23 | public BaseException(String errorCode) { 24 | this(errorCode, ""); 25 | } 26 | 27 | public BaseException(String errorCode, String detailMsg) { 28 | super(errorCode); 29 | this.defineCode = errorCode; 30 | this.chnDesc = detailMsg; 31 | } 32 | public BaseException newInstance(String message, Object... args) { 33 | BaseException ex = new BaseException(this.status, this.defineCode, this.chnDesc); 34 | message= this.chnDesc; 35 | ex.setMessage(message,args); 36 | return ex; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/liu/exceptions/BaseTradeException.java: -------------------------------------------------------------------------------- 1 | package com.liu.exceptions; 2 | 3 | /** 4 | * 5 | * @ClassName: BaseTradeException 6 | * @Description: trade core 异常类基类 7 | * @author 汪海霖 wanghl15@midea.com.cn 8 | * @date 2014-9-3 上午12:45:58 9 | */ 10 | public class BaseTradeException extends RuntimeException { 11 | 12 | /** 13 | * @Fields serialVersionUID : 14 | */ 15 | private static final long serialVersionUID = 3988229133456964977L; 16 | 17 | public BaseTradeException(String message) { 18 | super(message); 19 | } 20 | 21 | public BaseTradeException(Throwable e) { 22 | super(e); 23 | } 24 | 25 | public BaseTradeException(String message, Throwable cause) { 26 | super(message, cause); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/liu/exceptions/BusinessException.java: -------------------------------------------------------------------------------- 1 | package com.liu.exceptions; 2 | 3 | /** 4 | * 业务处理异常 5 | * @author xianqun.li 2015年12月30日 6 | * 7 | */ 8 | public class BusinessException extends MideaException { 9 | 10 | private static final long serialVersionUID = 1L; 11 | 12 | public static BusinessException UNKNOW_CARD_TYPE = new BusinessException(2001, "CARD_TYPE_ERROR", "未知的优惠券类型"); 13 | 14 | public static BusinessException IMPORT_DATA_EXCEPTION = new BusinessException(208, "IMPORT_DATA_INVALID", "导入数据不合法"); 15 | 16 | protected BusinessException(Integer status, String defineCode, String chnDesc) { 17 | super(status, defineCode, chnDesc); 18 | } 19 | 20 | public BusinessException newInstance(String msg ,Object... args){ 21 | BusinessException ex = new BusinessException(this.status, this.defineCode, this.chnDesc); 22 | ex.setMessage(msg, args); 23 | return ex ; 24 | } 25 | 26 | 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/liu/exceptions/MideaException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.liu.exceptions; 5 | 6 | import java.lang.reflect.Constructor; 7 | import java.text.MessageFormat; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.UUID; 11 | 12 | /** 13 | * 业务异常基类,所有业务异常都必须继承于此异常 14 | * 15 | * @author:wenhao.zeng 16 | * @version: 17 | */ 18 | 19 | public class MideaException extends RuntimeException{ 20 | 21 | private static final long serialVersionUID = -5097768787801034398L; 22 | 23 | /** 24 | * 异常ID,用于表示某一异常实例,每一个异常实例都有一个唯一的异常ID 25 | */ 26 | protected String id; 27 | 28 | /** 29 | * 异常信息,包含必要的上下文业务信息,用于打印日志 30 | */ 31 | protected String message; 32 | 33 | protected Integer status; 34 | 35 | protected String defineCode; 36 | 37 | protected String chnDesc; 38 | 39 | protected String realClassName; 40 | 41 | 42 | public MideaException(Throwable e){ 43 | super(); 44 | } 45 | 46 | protected MideaException(String defineCode) { 47 | super(); 48 | this.defineCode = defineCode; 49 | initId(); 50 | } 51 | 52 | protected MideaException(Integer status, String defineCode, String chnDesc) { 53 | super(); 54 | this.status = status; 55 | this.defineCode = defineCode; 56 | this.chnDesc = chnDesc; 57 | this.setMessage(this.chnDesc, null); 58 | initId(); 59 | } 60 | 61 | private void initId() { 62 | this.id = UUID.randomUUID().toString().toUpperCase().replaceAll("-", ""); 63 | } 64 | 65 | public String getId() { 66 | return id; 67 | } 68 | 69 | public String getMessage() { 70 | return message; 71 | } 72 | 73 | public void setMessage(String message, Object... args) { 74 | this.message = MessageFormat.format(message, args); 75 | } 76 | 77 | 78 | public String getDefineCode() { 79 | return defineCode; 80 | } 81 | 82 | public Integer getStatus(){ 83 | return status; 84 | } 85 | 86 | public String getChnDesc(){ 87 | return chnDesc; 88 | } 89 | 90 | public static T newException(T exception, String message, Object...args){ 91 | if(exception == null){ 92 | throw new RuntimeException("no exception instance specified"); 93 | } 94 | try { 95 | Constructor constructor = exception.getClass().getDeclaredConstructor(String.class); 96 | constructor.setAccessible(true); 97 | T newException = (T)constructor.newInstance(exception.getDefineCode()); 98 | newException.setMessage(message, args); 99 | return newException; 100 | } catch (Throwable e) { 101 | throw new RuntimeException("create exception instance fail : "+e.getMessage(), e); 102 | } 103 | } 104 | 105 | /** 106 | * 比较异常的class和defineCode是否相同 107 | * @param e 108 | * @return 109 | */ 110 | public boolean codeEquals(MideaException e){ 111 | if(e == null){ 112 | return false; 113 | } 114 | if(!e.getClass().equals(this.getClass())){ 115 | return false; 116 | } 117 | if(!e.getDefineCode().equals(getDefineCode())){ 118 | return false; 119 | } 120 | return true; 121 | } 122 | 123 | public MideaException upcasting() { 124 | if(this.getClass().equals(MideaException.class)){ 125 | return this; 126 | } 127 | MideaException superexception = new MideaException(this.status, this.defineCode,this.chnDesc); 128 | superexception.message = this.message; 129 | superexception.realClassName = this.getClass().getName(); 130 | superexception.id = this.id; 131 | superexception.setStackTrace(this.getStackTrace()); 132 | return superexception; 133 | } 134 | 135 | public MideaException downcasting(){ 136 | if(this.realClassName == null || MideaException.class.getName().equals(this.realClassName)){ 137 | return this; 138 | } 139 | Class clz = null; 140 | try{ 141 | clz = Class.forName(this.realClassName); 142 | }catch(Exception e){ 143 | } 144 | if(clz == null){ 145 | return this; 146 | } 147 | try { 148 | Constructor constructor = clz.getDeclaredConstructor(String.class); 149 | constructor.setAccessible(true); 150 | MideaException newException = (MideaException)constructor.newInstance(this.defineCode); 151 | newException.message = this.message; 152 | newException.id = this.id; 153 | newException.setStackTrace(this.getStackTrace()); 154 | return newException; 155 | } catch (Throwable e) { 156 | return this; 157 | } 158 | } 159 | 160 | public String getRealClassName() { 161 | if(realClassName==null){ 162 | return this.getClass().getName(); 163 | } 164 | return realClassName; 165 | } 166 | 167 | public StackTraceElement[] getCoreStackTrace(){ 168 | List list = new ArrayList(); 169 | for(StackTraceElement traceEle : getStackTrace()){ 170 | if(traceEle.getClassName().startsWith("com.midea.trade")){ 171 | list.add(traceEle); 172 | } 173 | } 174 | StackTraceElement[] stackTrace = new StackTraceElement[list.size()]; 175 | return list.toArray(stackTrace); 176 | } 177 | 178 | public String getCoreStackTraceStr(){ 179 | StringBuffer sb = new StringBuffer(); 180 | for(StackTraceElement traceEle : getCoreStackTrace()){ 181 | sb.append("\n"+traceEle.toString()); 182 | } 183 | return sb.toString(); 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /src/main/java/com/liu/exceptions/RedisClientException.java: -------------------------------------------------------------------------------- 1 | package com.liu.exceptions; 2 | 3 | /** 4 | * 5 | * @ClassName: RedisClientException 6 | * @Description: redis 操作异常类 7 | * @author 汪海霖 wanghl15@midea.com.cn 8 | * @date 2014-9-2 下午2:33:20 9 | */ 10 | public class RedisClientException extends BaseTradeException{ 11 | 12 | /** 13 | * @Fields serialVersionUID : 14 | */ 15 | private static final long serialVersionUID = 1027452261936311766L; 16 | 17 | /** 18 | * 构造异常对象 19 | * 20 | * @param msg 21 | */ 22 | public RedisClientException(String msg) { 23 | super(msg); 24 | } 25 | 26 | /** 27 | * RedisClientException 28 | * 29 | * @param exception 30 | */ 31 | public RedisClientException(Throwable exception) { 32 | super(exception); 33 | } 34 | 35 | /** 36 | * RedisClientException 37 | * 38 | * @param mag 39 | * @param exception 40 | */ 41 | public RedisClientException(String mag, Exception exception) { 42 | super(mag, exception); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/liu/exceptions/TradeSystemException.java: -------------------------------------------------------------------------------- 1 | package com.liu.exceptions; 2 | 3 | public class TradeSystemException extends BaseTradeException { 4 | 5 | /** 6 | * @Fields serialVersionUID : 7 | */ 8 | private static final long serialVersionUID = -6132660873946805356L; 9 | 10 | /** 11 | * 构造异常对象 12 | * 13 | * @param msg 14 | */ 15 | public TradeSystemException(String msg) { 16 | super(msg); 17 | } 18 | 19 | /** 20 | * TradeSystemException 21 | * 22 | * @param exception 23 | */ 24 | public TradeSystemException(Throwable exception) { 25 | super(exception); 26 | } 27 | 28 | /** 29 | * TradeSystemException 30 | * 31 | * @param mag 32 | * @param exception 33 | */ 34 | public TradeSystemException(String mag, Exception exception) { 35 | super(mag, exception); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/liu/groovy/LoadConfigGroovy.groovy: -------------------------------------------------------------------------------- 1 | package com.liu.groovy 2 | 3 | class LoadConfigGroovy { 4 | 5 | static String getConfig(def str){ 6 | println str; 7 | return "hello"+str; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/liu/groovy/TestLoadConfigGroovyMain.java: -------------------------------------------------------------------------------- 1 | package com.liu.groovy; 2 | 3 | import java.io.IOException; 4 | 5 | import groovy.lang.GroovyObject; 6 | import groovy.util.GroovyScriptEngine; 7 | import groovy.util.ResourceException; 8 | import groovy.util.ScriptException; 9 | 10 | public class TestLoadConfigGroovyMain { 11 | 12 | public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ResourceException, ScriptException{ 13 | String[] roots = new String[] { "src/main/java/com/liu/groovy/" }; 14 | // 通过指定的roots来初始化GroovyScriptEngine 15 | GroovyScriptEngine gse = new GroovyScriptEngine(roots); 16 | GroovyObject groovyObject = (GroovyObject) gse.loadScriptByName("LoadConfigGroovy.groovy").newInstance(); 17 | String result = (String) groovyObject.invokeMethod("getConfig", "你好"); 18 | System.out.println(result); 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/java/com/liu/kafka/KafkaClientMain.java: -------------------------------------------------------------------------------- 1 | package com.liu.kafka; 2 | 3 | import com.liu.kafka.consumer.KafkaConsumer; 4 | import com.liu.kafka.producer.KafkaProducer; 5 | 6 | public class KafkaClientMain { 7 | 8 | public static void main(String[] args) { 9 | KafkaProducer producer = new KafkaProducer(); 10 | producer.produce(); 11 | 12 | /*KafkaConsumer consumer = new KafkaConsumer(); 13 | consumer.consume();*/ 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/liu/kafka/consumer/KafkaConsumer.java: -------------------------------------------------------------------------------- 1 | package com.liu.kafka.consumer; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.Properties; 7 | 8 | import com.liu.kafka.producer.KafkaProducer; 9 | 10 | import kafka.consumer.ConsumerConfig; 11 | import kafka.consumer.ConsumerIterator; 12 | import kafka.consumer.KafkaStream; 13 | import kafka.javaapi.consumer.ConsumerConnector; 14 | import kafka.serializer.StringDecoder; 15 | import kafka.utils.VerifiableProperties; 16 | 17 | /** 18 | * 消息消费者 19 | * 20 | * 1. 搭建Storm集群 http://blog.csdn.net/ch717828/article/details/50718783 21 | * 2. kafka集群环境搭建 http://blog.csdn.net/ch717828/article/details/50748872 22 | * 3. storm+ kafka集成 http://blog.csdn.net/ch717828/article/details/50748912 23 | * @author liuzhihong 24 | * @date 2017年4月13日 上午11:33:11 25 | */ 26 | public class KafkaConsumer { 27 | 28 | private final ConsumerConnector consumer; 29 | 30 | public KafkaConsumer() { 31 | Properties props = new Properties(); 32 | 33 | // zookeeper 配置 34 | props.put("zookeeper.connect", "10.16.72.63:2181"); 35 | 36 | // 消费者所在组 37 | props.put("group.id", "kafka-group"); 38 | 39 | // zk连接超时 40 | props.put("zookeeper.session.timeout.ms", "10000"); 41 | props.put("zookeeper.sync.time.ms", "200"); 42 | props.put("auto.commit.interval.ms", "1000"); 43 | props.put("auto.offset.reset", "smallest"); 44 | 45 | // 序列化类 46 | props.put("serializer.class", "kafka.serializer.StringEncoder"); 47 | 48 | ConsumerConfig config = new ConsumerConfig(props); 49 | 50 | consumer = kafka.consumer.Consumer.createJavaConsumerConnector(config); 51 | } 52 | 53 | public void consume(){ 54 | Map topicCountMap = new HashMap(); 55 | topicCountMap.put(KafkaProducer.TOPIC, 1); 56 | 57 | StringDecoder keyDecoder = new StringDecoder(new VerifiableProperties()); 58 | StringDecoder valueDecoder = new StringDecoder(new VerifiableProperties()); 59 | 60 | Map>> consumerMap = 61 | consumer.createMessageStreams(topicCountMap, keyDecoder, valueDecoder); 62 | 63 | KafkaStream stream = consumerMap.get(KafkaProducer.TOPIC).get(0); 64 | 65 | ConsumerIterator it = stream.iterator(); 66 | int messageCount = 0; 67 | 68 | while(it.hasNext()){ 69 | System.out.println(it.next().message()); 70 | messageCount++; 71 | if(messageCount == 100){ 72 | System.out.println("Consumer端一共消费了" + messageCount + "条消息!"); 73 | } 74 | } 75 | 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/liu/kafka/producer/KafkaProducer.java: -------------------------------------------------------------------------------- 1 | package com.liu.kafka.producer; 2 | 3 | import java.util.Properties; 4 | 5 | import kafka.javaapi.producer.Producer; 6 | import kafka.producer.KeyedMessage; 7 | import kafka.producer.ProducerConfig; 8 | /** 9 | * kafka安装版本 kafka_2.10-0.8.2.2 10 | * 消息生产者 11 | * @author liuzhihong 12 | * @date 2017年4月13日 上午11:33:02 13 | */ 14 | public class KafkaProducer { 15 | 16 | public final static String TOPIC = "liu-topic-one"; 17 | 18 | private Producer producer; 19 | 20 | public KafkaProducer() { 21 | Properties properties = new Properties(); 22 | // 此处配置的是kafka的broker地址:端口列表 23 | properties.put("metadata.broker.list", "10.16.72.57:9092"); 24 | 25 | //配置value的序列化类 26 | properties.put("serializer.class", "kafka.serializer.StringEncoder"); 27 | 28 | //配置key的序列化类 29 | properties.put("key.serializer.class", "kafka.serializer.StringEncoder"); 30 | 31 | //request.required.acks 32 | //0, which means that the producer never waits for an acknowledgement from the broker (the same behavior as 0.7). This option provides the lowest latency but the weakest durability guarantees (some data will be lost when a server fails). 33 | //1, which means that the producer gets an acknowledgement after the leader replica has received the data. This option provides better durability as the client waits until the server acknowledges the request as successful (only messages that were written to the now-dead leader but not yet replicated will be lost). 34 | //-1, which means that the producer gets an acknowledgement after all in-sync replicas have received the data. This option provides the best durability, we guarantee that no messages will be lost as long as at least one in sync replica remains. 35 | properties.put("request.required.acks","1"); 36 | 37 | producer = new Producer(new ProducerConfig(properties)); 38 | } 39 | 40 | public void produce(){ 41 | int messageNo = 1; 42 | final int COUNT = 100; 43 | int messageCount = 0; 44 | while(messageNo <= COUNT){ 45 | String key = String.valueOf(messageNo); 46 | String data = "Hello , Kafka Message "+messageNo; 47 | producer.send(new KeyedMessage(TOPIC, key, data)); 48 | System.out.println(data); 49 | messageNo ++; 50 | messageCount++; 51 | } 52 | System.out.println("Priducer端一共产生了"+messageCount+"条消息!"); 53 | producer.close(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/liu/mq/MessageProducer.java: -------------------------------------------------------------------------------- 1 | package com.liu.mq; 2 | 3 | import javax.annotation.PostConstruct; 4 | 5 | import org.apache.commons.lang.StringUtils; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Component; 10 | 11 | import com.alibaba.rocketmq.client.exception.MQClientException; 12 | import com.alibaba.rocketmq.client.producer.DefaultMQProducer; 13 | import com.alibaba.rocketmq.client.producer.SendResult; 14 | import com.alibaba.rocketmq.client.producer.SendStatus; 15 | import com.alibaba.rocketmq.common.message.Message; 16 | import com.liu.enums.MqSendType; 17 | import com.liu.utils.JacksonMapper; 18 | 19 | /** 20 | * 21 | * @ClassName: MessageProducer 22 | * @Description: MQ消息生成类 23 | * @author 汪海霖 wanghl15@midea.com.cn 24 | * @date 2015-4-29 上午8:44:55 25 | */ 26 | 27 | @Component(value="messageProducer") 28 | public class MessageProducer { 29 | 30 | private static Logger logger = LoggerFactory.getLogger(MessageProducer.class); 31 | 32 | @Autowired 33 | private DefaultMQProducer defaultMQProducer; 34 | 35 | @PostConstruct 36 | public void initMq(){ 37 | try { 38 | defaultMQProducer.start(); 39 | } catch (MQClientException e) { 40 | } 41 | } 42 | 43 | public boolean sendMessage(MqSendType mqType,String key,String body){ 44 | if(StringUtils.isNotBlank(mqType.getPrefix())){ 45 | key = mqType.getPrefix().concat(key); 46 | } 47 | try{ 48 | Long startTime = System.currentTimeMillis(); 49 | Message msg = new Message(mqType.getTopic(), //topic 50 | mqType.getTag(), //tag 51 | key, //key 52 | body.getBytes()); //body 53 | SendResult sendResult = defaultMQProducer.send(msg); 54 | if(System.currentTimeMillis() - startTime > 100){ 55 | StringBuilder strBuff = new StringBuilder("mq消息发送耗时过长;topic=="); 56 | strBuff.append(mqType.getTopic()).append(";tag==").append(mqType.getTag()).append(";key==") 57 | .append(key).append(";总耗时==").append(System.currentTimeMillis() - startTime); 58 | logger.warn(strBuff.toString()); 59 | } 60 | return sendResult.getSendStatus() == SendStatus.SEND_OK; 61 | } catch (Exception ex){ 62 | StringBuilder strBuff = new StringBuilder("mq消息发送异常;mqType=="); 63 | strBuff.append(JacksonMapper.beanToJson(mqType)).append(";body==") 64 | .append(body).append(";error_msg==").append(ex.getMessage()); 65 | logger.error(strBuff.toString()); 66 | return false; 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/liu/netty/HelloClient.java: -------------------------------------------------------------------------------- 1 | package com.liu.netty; 2 | 3 | import com.liu.netty.client.handler.HelloClientIntHandler; 4 | 5 | import io.netty.bootstrap.Bootstrap; 6 | import io.netty.channel.ChannelFuture; 7 | import io.netty.channel.ChannelInitializer; 8 | import io.netty.channel.ChannelOption; 9 | import io.netty.channel.EventLoopGroup; 10 | import io.netty.channel.nio.NioEventLoopGroup; 11 | import io.netty.channel.socket.SocketChannel; 12 | import io.netty.channel.socket.nio.NioSocketChannel; 13 | 14 | public class HelloClient { 15 | 16 | public void connect(String host, int port) throws Exception { 17 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 18 | 19 | try { 20 | Bootstrap b = new Bootstrap(); 21 | b.group(workerGroup); 22 | b.channel(NioSocketChannel.class); 23 | b.option(ChannelOption.SO_KEEPALIVE, true); 24 | b.handler(new ChannelInitializer() { 25 | @Override 26 | public void initChannel(SocketChannel ch) throws Exception { 27 | ch.pipeline().addLast(new HelloClientIntHandler()); 28 | } 29 | }); 30 | 31 | // Start the client. 32 | ChannelFuture f = b.connect(host, port).sync(); 33 | 34 | // Wait until the connection is closed. 35 | f.channel().closeFuture().sync(); 36 | } finally { 37 | workerGroup.shutdownGracefully(); 38 | } 39 | 40 | } 41 | 42 | public static void main(String[] args) throws Exception { 43 | HelloClient client = new HelloClient(); 44 | client.connect("127.0.0.1", 8000); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/liu/netty/HelloServer.java: -------------------------------------------------------------------------------- 1 | package com.liu.netty; 2 | 3 | import com.liu.netty.server.handler.HelloServerInHandler; 4 | 5 | import io.netty.bootstrap.ServerBootstrap; 6 | import io.netty.channel.ChannelFuture; 7 | import io.netty.channel.ChannelInitializer; 8 | import io.netty.channel.ChannelOption; 9 | import io.netty.channel.EventLoopGroup; 10 | import io.netty.channel.nio.NioEventLoopGroup; 11 | import io.netty.channel.socket.SocketChannel; 12 | import io.netty.channel.socket.nio.NioServerSocketChannel; 13 | 14 | public class HelloServer { 15 | 16 | public void start(int port) throws Exception { 17 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 18 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 19 | try { 20 | ServerBootstrap b = new ServerBootstrap(); 21 | b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) 22 | .childHandler(new ChannelInitializer() { 23 | @Override 24 | public void initChannel(SocketChannel ch) 25 | throws Exception { 26 | // 注册handler 27 | ch.pipeline().addLast(new HelloServerInHandler()); 28 | } 29 | }).option(ChannelOption.SO_BACKLOG, 128) 30 | .childOption(ChannelOption.SO_KEEPALIVE, true); 31 | 32 | ChannelFuture f = b.bind(port).sync(); 33 | 34 | f.channel().closeFuture().sync(); 35 | } finally { 36 | workerGroup.shutdownGracefully(); 37 | bossGroup.shutdownGracefully(); 38 | } 39 | } 40 | 41 | public static void main(String[] args) throws Exception { 42 | HelloServer server = new HelloServer(); 43 | server.start(8000); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/liu/netty/client/handler/HelloClientIntHandler.java: -------------------------------------------------------------------------------- 1 | package com.liu.netty.client.handler; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import io.netty.buffer.ByteBuf; 7 | import io.netty.channel.ChannelHandlerContext; 8 | import io.netty.channel.ChannelInboundHandlerAdapter; 9 | 10 | public class HelloClientIntHandler extends ChannelInboundHandlerAdapter { 11 | 12 | private static Logger logger = LoggerFactory.getLogger(HelloClientIntHandler.class); 13 | 14 | // 接收server端的消息,并打印出来 15 | @Override 16 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 17 | logger.info("HelloClientIntHandler.channelRead"); 18 | ByteBuf result = (ByteBuf) msg; 19 | byte[] result1 = new byte[result.readableBytes()]; 20 | result.readBytes(result1); 21 | System.out.println("Server said:" + new String(result1)); 22 | result.release(); 23 | } 24 | 25 | // 连接成功后,向server发送消息 26 | @Override 27 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 28 | logger.info("HelloClientIntHandler.channelActive"); 29 | String msg = "Are you ok?"; 30 | ByteBuf encoded = ctx.alloc().buffer(4 * msg.length()); 31 | encoded.writeBytes(msg.getBytes()); 32 | ctx.write(encoded); 33 | ctx.flush(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/liu/netty/server/handler/HelloServerInHandler.java: -------------------------------------------------------------------------------- 1 | package com.liu.netty.server.handler; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import io.netty.buffer.ByteBuf; 7 | import io.netty.channel.ChannelHandlerContext; 8 | import io.netty.channel.ChannelInboundHandlerAdapter; 9 | 10 | public class HelloServerInHandler extends ChannelInboundHandlerAdapter { 11 | 12 | private static Logger logger = LoggerFactory 13 | .getLogger(HelloServerInHandler.class); 14 | 15 | @Override 16 | public void channelRead(ChannelHandlerContext ctx, Object msg) 17 | throws Exception { 18 | logger.info("HelloServerInHandler.channelRead"); 19 | ByteBuf result = (ByteBuf) msg; 20 | byte[] result1 = new byte[result.readableBytes()]; 21 | // msg中存储的是ByteBuf类型的数据,把数据读取到byte[]中 22 | result.readBytes(result1); 23 | String resultStr = new String(result1); 24 | // 接收并打印客户端的信息 25 | System.out.println("Client said:" + resultStr); 26 | // 释放资源,这行很关键 27 | result.release(); 28 | 29 | // 向客户端发送消息 30 | String response = "I am ok!"; 31 | // 在当前场景下,发送的数据必须转换成ByteBuf数组 32 | ByteBuf encoded = ctx.alloc().buffer(4 * response.length()); 33 | encoded.writeBytes(response.getBytes()); 34 | ctx.write(encoded); 35 | ctx.flush(); 36 | } 37 | 38 | @Override 39 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 40 | ctx.flush(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/liu/request/BaseRequest.java: -------------------------------------------------------------------------------- 1 | package com.liu.request; 2 | 3 | import com.liu.utils.ApiParamCheckUtil; 4 | 5 | public class BaseRequest { 6 | 7 | public String check() { 8 | return ApiParamCheckUtil.checkParam(this); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/liu/response/BaseResponse.java: -------------------------------------------------------------------------------- 1 | package com.liu.response; 2 | 3 | import java.io.Serializable; 4 | 5 | public class BaseResponse implements Serializable{ 6 | /** 7 | * 8 | */ 9 | private static final long serialVersionUID = 844524418947789561L; 10 | 11 | /** 12 | * 错误码,请求成功时该属性返回null,可以用该属性来判断请求是否成功 13 | */ 14 | private String errorCode; 15 | 16 | /** 17 | * 错误信息中文描述 18 | */ 19 | private String zhMsg; 20 | 21 | /** 22 | * 错误信息英文描述 23 | */ 24 | private String enMsg; 25 | 26 | /** 27 | * 中文详细信息 28 | */ 29 | private String zhDetailMsg; 30 | 31 | public String getErrorCode() { 32 | return errorCode; 33 | } 34 | public void setErrorCode(String errorCode) { 35 | this.errorCode = errorCode; 36 | } 37 | public String getZhMsg() { 38 | return zhMsg; 39 | } 40 | public void setZhMsg(String zhMsg) { 41 | this.zhMsg = zhMsg; 42 | } 43 | public String getEnMsg() { 44 | return enMsg; 45 | } 46 | public void setEnMsg(String enMsg) { 47 | this.enMsg = enMsg; 48 | } 49 | public String getZhDetailMsg() { 50 | return zhDetailMsg; 51 | } 52 | public void setZhDetailMsg(String zhDetailMsg) { 53 | this.zhDetailMsg = zhDetailMsg; 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/liu/shardingjdbc/SingleKeyModuloTableShardingAlgorithm.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 1999-2015 dangdang.com. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | *

16 | */ 17 | 18 | package com.liu.shardingjdbc; 19 | /** 20 | * 单分片字段支持三种方式equal,in,between,但是可以只实现其中一种 21 | */ 22 | import com.dangdang.ddframe.rdb.sharding.api.ShardingValue; 23 | import com.dangdang.ddframe.rdb.sharding.api.strategy.table.SingleKeyTableShardingAlgorithm; 24 | import com.google.common.collect.Range; 25 | 26 | import java.util.Collection; 27 | import java.util.LinkedHashSet; 28 | 29 | public class SingleKeyModuloTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm { 30 | 31 | @Override 32 | public String doEqualSharding(final Collection availableTargetNames, final ShardingValue shardingValue) { 33 | for (String each : availableTargetNames) { 34 | if (each.endsWith(shardingValue.getValue()+"")) { 35 | return each; 36 | } 37 | } 38 | throw new UnsupportedOperationException(); 39 | } 40 | 41 | @Override 42 | public Collection doInSharding(final Collection availableTargetNames, final ShardingValue shardingValue) { 43 | /*Collection result = new LinkedHashSet<>(availableTargetNames.size()); 44 | Collection values = shardingValue.getValues(); 45 | for (Integer value : values) { 46 | for (String each : availableTargetNames) { 47 | if (each.endsWith(value % 2 + "")) { 48 | result.add(each); 49 | } 50 | } 51 | } 52 | return result;*/ 53 | return null; 54 | } 55 | 56 | @Override 57 | public Collection doBetweenSharding(final Collection availableTargetNames, final ShardingValue shardingValue) { 58 | /* Collection result = new LinkedHashSet<>(availableTargetNames.size()); 59 | Range range = shardingValue.getValueRange(); 60 | for (Integer value = range.lowerEndpoint(); value <= range.upperEndpoint(); value++) { 61 | for (String each : availableTargetNames) { 62 | if (each.endsWith(value % 2 + "")) { 63 | result.add(each); 64 | } 65 | } 66 | } 67 | return result;*/ 68 | return null; 69 | } 70 | } -------------------------------------------------------------------------------- /src/main/java/com/liu/spring/AppSpringContext.java: -------------------------------------------------------------------------------- 1 | package com.liu.spring; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | import org.springframework.util.Assert; 7 | 8 | public class AppSpringContext implements ApplicationContextAware{ 9 | 10 | private static ApplicationContext applicationContext; 11 | 12 | @Override 13 | public void setApplicationContext(ApplicationContext appContext) 14 | throws BeansException { 15 | AppSpringContext.applicationContext = appContext; 16 | } 17 | 18 | /** 19 | * @return ApplicationContext 20 | */ 21 | public static ApplicationContext getApplicationContext() { 22 | return applicationContext; 23 | } 24 | /** 25 | * 获取bean对象 26 | * @param clazz 27 | * @return 28 | */ 29 | public static T getBean(Class clazz){ 30 | Assert.notNull(applicationContext, "Application Context not initialize"); 31 | return applicationContext.getBean(clazz); 32 | } 33 | /** 34 | * 获取 bean 对象 35 | * @param beanName 36 | * @param clazz 37 | * @return 38 | */ 39 | public static T getBean(String beanName,Class clazz){ 40 | Assert.notNull(applicationContext, "Application Context not initialize"); 41 | return applicationContext.getBean(beanName, clazz); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/ApiParamCheckUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.liu.utils; 5 | 6 | import java.util.Set; 7 | 8 | import javax.validation.ConstraintViolation; 9 | import javax.validation.Validation; 10 | import javax.validation.Validator; 11 | import javax.validation.ValidatorFactory; 12 | 13 | /** 14 | * @ClassName: ApiParamCheckUtil 15 | * @Description: 订单 16 | * @author 汪海霖 wanghl15@midea.com.cn 17 | * @date 2014-9-28 下午2:31:31 18 | */ 19 | public class ApiParamCheckUtil { 20 | 21 | private static Validator validator = null; 22 | 23 | public static String checkParam(T obj){ 24 | if(validator == null){ 25 | ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); 26 | validator = validatorFactory.getValidator(); 27 | } 28 | Set> valideSet = validator.validate(obj); 29 | if(valideSet != null && valideSet.size() > 0){ 30 | StringBuilder strBuff = new StringBuilder(); 31 | for(ConstraintViolation cv : valideSet){ 32 | strBuff.append(cv.getPropertyPath()).append(":").append(cv.getMessage()).append(";"); 33 | } 34 | return strBuff.toString(); 35 | }else{ 36 | return null; 37 | } 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/CSVUtil.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.BufferedWriter; 5 | import java.io.File; 6 | import java.io.FileOutputStream; 7 | import java.io.FileReader; 8 | import java.io.IOException; 9 | import java.io.OutputStreamWriter; 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * CSV操作(导出和导入) 15 | * @author wujun10 16 | * 17 | */ 18 | public class CSVUtil { 19 | 20 | /** 21 | * 导出 22 | * @param file 23 | * @param dataList 24 | * @return 25 | */ 26 | public static boolean exportCsv(File file, List dataList) { 27 | boolean isSucess = false; 28 | 29 | FileOutputStream out = null; 30 | OutputStreamWriter osw = null; 31 | BufferedWriter bw = null; 32 | try { 33 | out = new FileOutputStream(file); 34 | osw = new OutputStreamWriter(out, "GBK"); 35 | bw = new BufferedWriter(osw); 36 | if (dataList != null && !dataList.isEmpty()) { 37 | for (String data : dataList) { 38 | bw.append(data).append(","); 39 | bw.newLine(); 40 | } 41 | } 42 | isSucess = true; 43 | } catch (Exception e) { 44 | isSucess = false; 45 | } finally { 46 | if (bw != null) { 47 | try { 48 | bw.close(); 49 | bw = null; 50 | } catch (IOException e) { 51 | e.printStackTrace(); 52 | } 53 | } 54 | if (osw != null) { 55 | try { 56 | osw.close(); 57 | osw = null; 58 | } catch (IOException e) { 59 | e.printStackTrace(); 60 | } 61 | } 62 | if (out != null) { 63 | try { 64 | out.close(); 65 | out = null; 66 | } catch (IOException e) { 67 | e.printStackTrace(); 68 | } 69 | } 70 | } 71 | 72 | return isSucess; 73 | } 74 | 75 | /** 76 | * 导入 77 | * @param file 78 | * @return 79 | */ 80 | public static List importCsv(File file) { 81 | List dataList = new ArrayList(); 82 | 83 | BufferedReader br = null; 84 | try { 85 | br = new BufferedReader(new FileReader(file)); 86 | String line = ""; 87 | while ((line = br.readLine()) != null) { 88 | dataList.add(line); 89 | } 90 | } catch (Exception e) { 91 | } finally { 92 | if (br != null) { 93 | try { 94 | br.close(); 95 | br = null; 96 | } catch (IOException e) { 97 | e.printStackTrace(); 98 | } 99 | } 100 | } 101 | 102 | return dataList; 103 | } 104 | 105 | public static void main(String[] args) { 106 | List dataList=new ArrayList(); 107 | dataList.add("1,张三,男,"); 108 | dataList.add("2,李四,男,"); 109 | dataList.add("3,小红,女,"); 110 | boolean isSuccess=CSVUtil.exportCsv(new File("D:/filetemp/ljq.csv"), dataList); 111 | System.out.println(isSuccess); 112 | } 113 | } -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/ClassUtils.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.net.URL; 6 | import java.util.ArrayList; 7 | import java.util.Enumeration; 8 | import java.util.List; 9 | /** 10 | * 找到该接口所有的实现类 11 | * @author liuzhihong 12 | * @date 2016年4月9日 下午2:14:05 13 | */ 14 | public class ClassUtils { 15 | @SuppressWarnings({ "rawtypes", "unchecked" }) 16 | public static List getAllClassByInterface(Class c) { 17 | List returnClassList = new ArrayList(); 18 | if (c.isInterface()) { 19 | String packageName = c.getPackage().getName(); 20 | try { 21 | List allClass = getClasses(packageName); 22 | for (int i = 0; i < allClass.size(); i++) { 23 | if (c.isAssignableFrom(allClass.get(i))) { 24 | if (!c.equals(allClass.get(i))) { 25 | returnClassList.add(allClass.get(i)); 26 | } 27 | } 28 | } 29 | } catch (ClassNotFoundException e) { 30 | e.printStackTrace(); 31 | } catch (IOException e) { 32 | e.printStackTrace(); 33 | } 34 | } 35 | return returnClassList; 36 | } 37 | 38 | @SuppressWarnings("rawtypes") 39 | private static List getClasses(String packageName) throws ClassNotFoundException, IOException { 40 | ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 41 | String path = packageName.replace('.', '/'); 42 | Enumeration resources = classLoader.getResources(path); 43 | List dirs = new ArrayList(); 44 | while (resources.hasMoreElements()) { 45 | URL resource = resources.nextElement(); 46 | dirs.add(new File(resource.getFile())); 47 | } 48 | ArrayList classes = new ArrayList(); 49 | for (File directory : dirs) { 50 | classes.addAll(findClasses(directory, packageName)); 51 | } 52 | return classes; 53 | } 54 | 55 | @SuppressWarnings("rawtypes") 56 | private static List findClasses(File directory, String packageName) throws ClassNotFoundException { 57 | List classes = new ArrayList(); 58 | if (!directory.exists()) { 59 | return classes; 60 | } 61 | File[] files = directory.listFiles(); 62 | for (File file : files) { 63 | if (file.isDirectory()) { 64 | assert!file.getName().contains("."); 65 | classes.addAll(findClasses(file, packageName + "." + file.getName())); 66 | } else if (file.getName().endsWith(".class")) { 67 | classes.add( 68 | Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); 69 | } 70 | } 71 | return classes; 72 | } 73 | } -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/ClientBuilder.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.util.Properties; 4 | 5 | import org.apache.commons.lang.StringUtils; 6 | import org.elasticsearch.client.Client; 7 | import org.elasticsearch.client.transport.TransportClient; 8 | import org.elasticsearch.common.settings.ImmutableSettings; 9 | import org.elasticsearch.common.settings.Settings; 10 | import org.elasticsearch.common.transport.InetSocketTransportAddress; 11 | import org.elasticsearch.shield.authc.support.SecuredString; 12 | import org.elasticsearch.shield.authc.support.UsernamePasswordToken; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | 16 | /** 17 | * @author kdl 18 | * @Title 19 | * @Description elasticsearch搜索引擎 20 | * http://es.xiaoleilu.com/010_Intro/05_What_is_it.html 21 | */ 22 | public class ClientBuilder { 23 | 24 | private static Logger logger = LoggerFactory.getLogger(ClientBuilder.class); 25 | 26 | private static String es; 27 | /* 28 | * @Value("") private String connectUrl; 29 | */ 30 | 31 | /** 32 | * 静态,单例... 33 | */ 34 | // private static JestClient JestClient; 35 | private static Client client; 36 | 37 | /** 38 | * @author chejy 39 | * @Description: 建立连接 40 | * @return JestClient 返回类型 41 | * @throws 42 | */ 43 | public static Client getJestClient() { 44 | /* 45 | * Settings settings = ImmutableSettings.settingsBuilder() 46 | * .put("cluster.name", "elasticsearch").build(); 47 | */ 48 | // 你可以设置client.transport.sniff为true来使客户端去嗅探整个集群的状态, 49 | // 把集群中其它机器的ip地址加到客户端中,这样做的好处是一般你不用手动设置集群里所有集群的ip到连接客户端, 50 | // 它会自动帮你添加,并且自动发现新加入集群的机器 51 | /* 52 | * Settings settings = ImmutableSettings.settingsBuilder() 53 | * .put("client.transport.sniff", true).build(); 54 | */ 55 | Properties properties = new Properties(); 56 | /*StringBuffer path = new StringBuffer(); 57 | path.append( 58 | ClientBuilder.class.getClassLoader().getResource("") 59 | .getPath()).append("fc_config.properties"); 60 | InputStream inputStream = new FileInputStream(path.toString()); 61 | properties.load(inputStream); 62 | inputStream.close(); // 关闭流 63 | String es = properties.getProperty("elasticsearch");*/ 64 | if (client == null) { 65 | if (StringUtils.isNotBlank(es) && es.equals("prod")) { 66 | Settings settings = ImmutableSettings.settingsBuilder() 67 | .put("cluster.name", "elasticsearch") 68 | .put("shield.user", "t_admin:v0SPxQzqN^fKV4e&").build(); 69 | client = new TransportClient(settings) 70 | .addTransportAddress(new InetSocketTransportAddress("10.169.11.248", 9300)) 71 | .addTransportAddress(new InetSocketTransportAddress("10.251.232.163", 9300)) 72 | .addTransportAddress(new InetSocketTransportAddress("10.117.59.86", 9300)); 73 | String token = UsernamePasswordToken.basicAuthHeaderValue("t_admin", 74 | new SecuredString("v0SPxQzqN^fKV4e&".toCharArray())); 75 | client.prepareSearch().putHeader("Authorization", token); 76 | } else if (StringUtils.isNotBlank(es) && es.equals("stress")) { 77 | // 压测、beta、开发 78 | Settings settings = ImmutableSettings.settingsBuilder() 79 | .put("cluster.name", "elasticsearch_HA") 80 | .put("shield.user", "t_admin:123456").build(); 81 | client = new TransportClient(settings) 82 | .addTransportAddress(new InetSocketTransportAddress("121.41.74.247",9300)) 83 | .addTransportAddress(new InetSocketTransportAddress("120.26.225.182",9300)); 84 | String token = UsernamePasswordToken.basicAuthHeaderValue( 85 | "t_admin", new SecuredString("123456".toCharArray())); 86 | client.prepareSearch().putHeader("Authorization", token); 87 | } else { 88 | Settings settings = ImmutableSettings.settingsBuilder() 89 | .put("cluster.name", "my-application-1").build(); 90 | client = new TransportClient(settings) 91 | .addTransportAddress(new InetSocketTransportAddress("10.16.72.57", 9300)); 92 | } 93 | } 94 | return client; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/DataExportWebUtils.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.IOException; 5 | import java.io.OutputStream; 6 | import java.io.OutputStreamWriter; 7 | import java.util.ArrayList; 8 | import java.util.Date; 9 | import java.util.Iterator; 10 | import java.util.LinkedHashMap; 11 | import java.util.List; 12 | import java.util.Map; 13 | import java.util.regex.Matcher; 14 | import java.util.regex.Pattern; 15 | 16 | import javax.servlet.http.HttpServletResponse; 17 | 18 | import org.apache.commons.beanutils.BeanUtils; 19 | import org.apache.commons.beanutils.PropertyUtils; 20 | import org.apache.commons.collections.CollectionUtils; 21 | import org.apache.commons.lang.StringUtils; 22 | import org.apache.poi.xssf.usermodel.XSSFCell; 23 | import org.apache.poi.xssf.usermodel.XSSFCellStyle; 24 | import org.apache.poi.xssf.usermodel.XSSFRichTextString; 25 | import org.apache.poi.xssf.usermodel.XSSFRow; 26 | import org.apache.poi.xssf.usermodel.XSSFSheet; 27 | import org.apache.poi.xssf.usermodel.XSSFWorkbook; 28 | 29 | public class DataExportWebUtils { 30 | 31 | /** 32 | * 指定哪些数据需要通过数字转字符的方式以避免科学记数法 33 | */ 34 | private String keys = ""; 35 | 36 | @SuppressWarnings({ "rawtypes", "unchecked"}) 37 | public static void exportExcel(List exportData, Map columnMapper,String fileName , HttpServletResponse res) throws Exception{ 38 | 39 | OutputStream out = res.getOutputStream(); 40 | 41 | LinkedHashMap rowMapper = new LinkedHashMap(); 42 | for (Iterator propertyIterator = columnMapper.entrySet().iterator(); propertyIterator.hasNext();) { 43 | java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); 44 | rowMapper.put(propertyEntry.getKey(), propertyEntry.getValue()); 45 | } 46 | String[] headers = mapToArrayByValue(rowMapper); 47 | // 声明一个工作薄 48 | XSSFWorkbook workbook = new XSSFWorkbook(); 49 | // 生成一个表格 50 | XSSFSheet sheet = workbook.createSheet(fileName); 51 | // 设置表格默认列宽度为15个字节 52 | sheet.setDefaultColumnWidth((short) 15); 53 | // 生成一个样式 54 | XSSFCellStyle style = workbook.createCellStyle(); 55 | // 设置这些样式 56 | // 生成并设置另一个样式 57 | XSSFCellStyle style2 = workbook.createCellStyle(); 58 | 59 | // 产生表格标题行 60 | XSSFRow row = sheet.createRow(0); 61 | for (short i = 0; i < headers.length; i++) { 62 | XSSFCell cell = row.createCell(i); 63 | cell.setCellStyle(style); 64 | XSSFRichTextString text = new XSSFRichTextString(headers[i]); 65 | cell.setCellValue(text); 66 | } 67 | 68 | // 遍历集合数据,产生数据行 69 | Iterator it = exportData.iterator(); 70 | int index = 0; 71 | while (it.hasNext()) { 72 | index++; 73 | row = sheet.createRow(index); 74 | XSSFCell cell = null; 75 | Object rowObject = (Object) it.next(); 76 | 77 | String[] fields = mapToArrayByKey(rowMapper); 78 | for (int i = 0; i < fields.length; i++) { 79 | Object val = null; 80 | try { 81 | val = PropertyUtils.getProperty(rowObject, fields[i]); 82 | cell = row.createCell((short) i); 83 | cell.setCellStyle(style2); 84 | String value = null; 85 | if (val instanceof Date) { 86 | value = (val == null ? null : DateUtils.getDateStr((Date) val)); 87 | } else { 88 | value = (val == null ? null : val.toString()); 89 | } 90 | if (BeanUtils.getProperty(rowObject, fields[i]) != null) { 91 | Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d{1,5})?$"); 92 | Matcher matcher = pattern.matcher(value); 93 | if (matcher.find()) { 94 | //value = value + "\t"; // 避免数字变成科学计数法,前后加\t,或前面加= 95 | cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC); 96 | if(StringUtils.length(value) >= 12 ){ 97 | cell.setCellValue(value); 98 | }else{ 99 | cell.setCellValue(new Double(value)); 100 | } 101 | } else { 102 | XSSFRichTextString richString = new XSSFRichTextString(value); 103 | cell.setCellValue(richString); 104 | } 105 | } 106 | } catch (Exception e) { 107 | e.printStackTrace(); 108 | } 109 | } 110 | } 111 | 112 | try { 113 | workbook.write(out); 114 | out.flush(); 115 | } catch (IOException e) { 116 | e.printStackTrace(); 117 | } finally { 118 | // 关闭资源 119 | if (null != out) { 120 | try { 121 | out.close(); 122 | } catch (IOException e) { 123 | e.printStackTrace(); 124 | } 125 | } 126 | } 127 | } 128 | 129 | 130 | @SuppressWarnings("rawtypes") 131 | public static String[] mapToArrayByValue(Map columnMapper) { 132 | List arrayList = new ArrayList(); 133 | for (Iterator propertyIterator = columnMapper.entrySet().iterator(); propertyIterator.hasNext();) { 134 | java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); 135 | arrayList.add(propertyEntry.getValue().toString()); 136 | } 137 | return arrayList.toArray(new String[arrayList.size()]); 138 | } 139 | 140 | /** 141 | * 由map中的key构成数组 142 | * 143 | * @param columnMapper 144 | * @return 145 | */ 146 | @SuppressWarnings("rawtypes") 147 | public static String[] mapToArrayByKey(Map columnMapper) { 148 | List arrayList = new ArrayList(); 149 | for (Iterator propertyIterator = columnMapper.entrySet().iterator(); propertyIterator.hasNext();) { 150 | java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); 151 | arrayList.add(propertyEntry.getKey().toString()); 152 | } 153 | return arrayList.toArray(new String[arrayList.size()]); 154 | } 155 | 156 | /** 157 | * 导出csv文件 158 | * 2016年3月11日 下午8:17:14 159 | * @param exportData 160 | * @param columnMapper 161 | * @param res 162 | * 163 | */ 164 | @SuppressWarnings("rawtypes") 165 | public void exportCsv(List exportData, Map columnMapper,HttpServletResponse res) { 166 | BufferedWriter csvFileOutputStream = null; 167 | LinkedHashMap rowMapper = getExportPurchaseOrderClomn(columnMapper); 168 | try { 169 | // GB2312使正确读取分隔符"," 170 | csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(res.getOutputStream(), "gb2312"), 1024); 171 | // 写入文件头部 172 | for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator.hasNext();) { 173 | java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); 174 | csvFileOutputStream.write("\""+ propertyEntry.getValue().toString() + "\""); 175 | if (propertyIterator.hasNext()) { 176 | csvFileOutputStream.write(","); 177 | } 178 | } 179 | csvFileOutputStream.newLine(); 180 | 181 | // 写入文件内容 182 | if (CollectionUtils.isNotEmpty(exportData)) { 183 | for (Iterator iterator = exportData.iterator(); iterator.hasNext();) { 184 | Object row = (Object) iterator.next(); 185 | for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator.hasNext();) { 186 | java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); 187 | String value = BeanUtils.getProperty(row, propertyEntry.getKey().toString()); 188 | if(BeanUtils.getProperty(row, propertyEntry.getKey().toString()) != null){ 189 | value = changeNum2Str(propertyEntry.getKey().toString(), value); 190 | csvFileOutputStream.write("\""+ value + "\""); 191 | } 192 | if (propertyIterator.hasNext()) { 193 | csvFileOutputStream.write(","); 194 | } 195 | } 196 | if (iterator.hasNext()) { 197 | csvFileOutputStream.newLine(); 198 | } 199 | } 200 | } 201 | 202 | csvFileOutputStream.flush(); 203 | } catch (Exception e) { 204 | e.printStackTrace(); 205 | } finally { 206 | try { 207 | if(csvFileOutputStream != null){ 208 | csvFileOutputStream.close(); 209 | } 210 | } catch (IOException e) { 211 | e.printStackTrace(); 212 | } 213 | } 214 | } 215 | 216 | 217 | @SuppressWarnings({ "rawtypes", "unchecked" }) 218 | private LinkedHashMap getExportPurchaseOrderClomn(Map exportColumn){ 219 | LinkedHashMap rowMapper = new LinkedHashMap (); 220 | for (Iterator propertyIterator = exportColumn.entrySet().iterator(); propertyIterator.hasNext();) { 221 | java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); 222 | rowMapper.put(propertyEntry.getKey(), propertyEntry.getValue()); 223 | } 224 | return rowMapper; 225 | } 226 | 227 | /** 228 | * 处理导出文件的数字 229 | * 避免变成科学记数法 230 | * 2016年3月11日 下午8:15:24 231 | * @param key 232 | * @param value 233 | * @return 234 | * 235 | * 236 | */ 237 | public String changeNum2Str(String key, String value){ 238 | if(keys.contains(key)){ 239 | value = value + "\t"; 240 | } 241 | return value; 242 | } 243 | public static void main(String[] args) { 244 | System.out.println("1234.5433".matches("^-?\\d+(\\.\\d{1,5})?$")); 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/DateUtils.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.text.DateFormat; 4 | import java.text.ParseException; 5 | import java.text.SimpleDateFormat; 6 | import java.util.Date; 7 | import java.util.TreeSet; 8 | 9 | public class DateUtils { 10 | 11 | public static Date getDateFromStr(String str) throws Exception { 12 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 13 | Date date = sdf.parse(str); 14 | return date; 15 | } 16 | 17 | public static Date getDateFromyyyyMM(String date) { 18 | try { 19 | return new SimpleDateFormat("yyyy-MM").parse(date); 20 | } catch (ParseException e) { 21 | return null; 22 | } 23 | } 24 | 25 | public static Date getOldDate(Date... dates) { 26 | 27 | TreeSet dateTreeSet = new TreeSet(); 28 | for (Date date : dates) { 29 | if (date != null) dateTreeSet.add(date); 30 | } 31 | return dateTreeSet.first(); 32 | } 33 | 34 | public static Date getLastDate(Date... dates) { 35 | 36 | TreeSet dateTreeSet = new TreeSet(); 37 | for (Date date : dates) { 38 | if (date != null) dateTreeSet.add(date); 39 | } 40 | return dateTreeSet.last(); 41 | } 42 | 43 | public static Date getDayFromStr(String str) throws Exception { 44 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 45 | Date date = sdf.parse(str); 46 | return date; 47 | } 48 | 49 | public static String getDateStr(Date date, String format) { 50 | DateFormat df = new SimpleDateFormat(format); 51 | return df.format(date); 52 | } 53 | 54 | public static String getDateStr(Date date) { 55 | 56 | DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 57 | 58 | return df.format(date); 59 | } 60 | 61 | public static String getDayStr(Date date) { 62 | 63 | DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 64 | 65 | return df.format(date); 66 | } 67 | 68 | public static void main(String[] args) throws Exception { 69 | System.out.println(getDayFromStr("2015-12-10")); 70 | ; 71 | } 72 | 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/ExcelUtils.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.io.OutputStream; 9 | import java.text.DecimalFormat; 10 | import java.util.ArrayList; 11 | import java.util.Date; 12 | import java.util.Iterator; 13 | import java.util.LinkedHashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | import java.util.regex.Matcher; 17 | import java.util.regex.Pattern; 18 | 19 | import org.apache.commons.beanutils.BeanUtils; 20 | import org.apache.commons.beanutils.PropertyUtils; 21 | import org.apache.commons.lang.StringUtils; 22 | import org.apache.poi.hssf.usermodel.HSSFCell; 23 | import org.apache.poi.hssf.usermodel.HSSFCellStyle; 24 | import org.apache.poi.hssf.usermodel.HSSFRichTextString; 25 | import org.apache.poi.hssf.usermodel.HSSFRow; 26 | import org.apache.poi.hssf.usermodel.HSSFSheet; 27 | import org.apache.poi.hssf.usermodel.HSSFWorkbook; 28 | import org.apache.poi.openxml4j.exceptions.InvalidFormatException; 29 | import org.apache.poi.ss.usermodel.Cell; 30 | import org.apache.poi.ss.usermodel.CellValue; 31 | import org.apache.poi.ss.usermodel.DateUtil; 32 | import org.apache.poi.ss.usermodel.FormulaEvaluator; 33 | import org.apache.poi.ss.usermodel.Row; 34 | import org.apache.poi.ss.usermodel.Sheet; 35 | import org.apache.poi.ss.usermodel.Workbook; 36 | import org.apache.poi.ss.usermodel.WorkbookFactory; 37 | 38 | import com.liu.code.FileUploadApiCode; 39 | import com.liu.exceptions.BaseException; 40 | import com.liu.exceptions.BusinessException; 41 | import com.liu.exceptions.MideaException; 42 | 43 | public class ExcelUtils { 44 | 45 | /** 46 | * 导出 47 | * 48 | * @param exportData 49 | * 导出数据 50 | * @param rowMapper 51 | * 导出列 52 | * @param outPutPath 53 | * 文件存放路径 54 | * @param filename 55 | * 导出文件名 56 | * @return 57 | */ 58 | @SuppressWarnings({ "rawtypes", "unchecked", "deprecation" }) 59 | public static File exportExcel(List exportData, Map columnMapper, String outPutPath, String filename) { 60 | OutputStream out = null; 61 | File xlsFile = new File(outPutPath +File.separator+filename + ".xls"); 62 | File parent = xlsFile.getParentFile(); 63 | if (parent != null && !parent.exists()) { 64 | parent.mkdirs(); 65 | } 66 | try { 67 | xlsFile.createNewFile(); 68 | out = new FileOutputStream(xlsFile); 69 | } catch (IOException e1) { 70 | e1.printStackTrace(); 71 | } 72 | LinkedHashMap rowMapper = new LinkedHashMap(); 73 | for (Iterator propertyIterator = columnMapper.entrySet().iterator(); propertyIterator.hasNext();) { 74 | java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); 75 | rowMapper.put(propertyEntry.getKey(), propertyEntry.getValue()); 76 | } 77 | String[] headers = mapToArrayByValue(rowMapper); 78 | // 声明一个工作薄 79 | HSSFWorkbook workbook = new HSSFWorkbook(); 80 | // 生成一个表格 81 | HSSFSheet sheet = workbook.createSheet(filename); 82 | // 设置表格默认列宽度为15个字节 83 | sheet.setDefaultColumnWidth((short) 15); 84 | // 生成一个样式 85 | HSSFCellStyle style = workbook.createCellStyle(); 86 | // 设置这些样式 87 | // 生成并设置另一个样式 88 | HSSFCellStyle style2 = workbook.createCellStyle(); 89 | 90 | // 产生表格标题行 91 | HSSFRow row = sheet.createRow(0); 92 | for (short i = 0; i < headers.length; i++) { 93 | HSSFCell cell = row.createCell(i); 94 | cell.setCellStyle(style); 95 | HSSFRichTextString text = new HSSFRichTextString(headers[i]); 96 | cell.setCellValue(text); 97 | } 98 | 99 | // 遍历集合数据,产生数据行 100 | Iterator it = exportData.iterator(); 101 | int index = 0; 102 | while (it.hasNext()) { 103 | index++; 104 | row = sheet.createRow(index); 105 | HSSFCell cell = null; 106 | Object rowObject = (Object) it.next(); 107 | 108 | String[] fields = mapToArrayByKey(rowMapper); 109 | for (int i = 0; i < fields.length; i++) { 110 | Object val = null; 111 | try { 112 | val = PropertyUtils.getProperty(rowObject, fields[i]); 113 | cell = row.createCell((short) i); 114 | cell.setCellStyle(style2); 115 | String value = null; 116 | if (val instanceof Date) { 117 | value = (val == null ? null : DateUtils.getDateStr((Date) val)); 118 | } else { 119 | value = (val == null ? null : val.toString()); 120 | } 121 | if (BeanUtils.getProperty(rowObject, fields[i]) != null) { 122 | Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d{1,5})?$"); 123 | Matcher matcher = pattern.matcher(value); 124 | if (matcher.find()) { 125 | value = value + "\t"; // 避免数字变成科学计数法,前后加\t,或前面加= 126 | cell.setCellValue(value); 127 | } else { 128 | HSSFRichTextString richString = new HSSFRichTextString(value); 129 | cell.setCellValue(richString); 130 | } 131 | } 132 | } catch (Exception e) { 133 | e.printStackTrace(); 134 | } 135 | } 136 | } 137 | 138 | try { 139 | workbook.write(out); 140 | } catch (IOException e) { 141 | e.printStackTrace(); 142 | } finally { 143 | // 关闭资源 144 | if (null != out) { 145 | try { 146 | out.close(); 147 | } catch (IOException e) { 148 | e.printStackTrace(); 149 | } 150 | } 151 | } 152 | return xlsFile; 153 | } 154 | 155 | @SuppressWarnings("rawtypes") 156 | public static String[] mapToArrayByValue(Map columnMapper) { 157 | List arrayList = new ArrayList(); 158 | for (Iterator propertyIterator = columnMapper.entrySet().iterator(); propertyIterator.hasNext();) { 159 | java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); 160 | arrayList.add(propertyEntry.getValue().toString()); 161 | } 162 | return arrayList.toArray(new String[arrayList.size()]); 163 | } 164 | 165 | /** 166 | * 由map中的key构成数组 167 | * 168 | * @param columnMapper 169 | * @return 170 | */ 171 | @SuppressWarnings("rawtypes") 172 | public static String[] mapToArrayByKey(Map columnMapper) { 173 | List arrayList = new ArrayList(); 174 | for (Iterator propertyIterator = columnMapper.entrySet().iterator(); propertyIterator.hasNext();) { 175 | java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); 176 | arrayList.add(propertyEntry.getKey().toString()); 177 | } 178 | return arrayList.toArray(new String[arrayList.size()]); 179 | } 180 | 181 | /** 182 | * 导入 183 | */ 184 | public static List> readFromExcel(InputStream inputStream) { 185 | DecimalFormat df = new DecimalFormat("#.00"); 186 | try { 187 | Workbook wb = WorkbookFactory.create(inputStream); 188 | FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); 189 | // int sheetNum = wb.getNumberOfSheets(); 190 | Sheet sheet = wb.getSheetAt(0); 191 | int startRow = sheet.getFirstRowNum() + 1; 192 | int endRow = sheet.getLastRowNum(); 193 | if (endRow > 1000) { 194 | throw BusinessException.IMPORT_DATA_EXCEPTION.newInstance("一次最多不能超过1000条数据,超出时请分批导入", ""); 195 | } 196 | 197 | List> excelData = new ArrayList>(); 198 | for (int i = startRow; i <= endRow; i++) { 199 | Row row = sheet.getRow(i); 200 | List rowData = new ArrayList(); 201 | StringBuffer auditEmptyRow = new StringBuffer(); 202 | if (row != null) { 203 | int cellNum = row.getLastCellNum(); 204 | for (int j = 0; j < cellNum; j++) { 205 | StringBuffer value = new StringBuffer(); 206 | Cell cell = row.getCell(j); 207 | CellValue cellValue = evaluator.evaluate(cell); 208 | if (cellValue != null) { 209 | switch (cellValue.getCellType()) { 210 | case Cell.CELL_TYPE_BOOLEAN: 211 | value.append(cellValue.getBooleanValue()); 212 | break; 213 | case Cell.CELL_TYPE_NUMERIC: 214 | if (DateUtil.isCellDateFormatted(cell)) { 215 | value.append(cell.getDateCellValue()); 216 | } else { 217 | //value.append(cellValue.getNumberValue()+""); 218 | value.append(df.format(cellValue.getNumberValue())); 219 | } 220 | break; 221 | case Cell.CELL_TYPE_STRING: 222 | value.append(cellValue.getStringValue().trim()); 223 | break; 224 | default: 225 | value.append(""); 226 | break; 227 | } 228 | } 229 | auditEmptyRow.append(value.toString().trim()); 230 | if (StringUtils.isBlank(value.toString())) { 231 | rowData.add(null); 232 | } else { 233 | rowData.add(value.toString()); 234 | } 235 | } 236 | } 237 | if (StringUtils.isNotBlank(auditEmptyRow.toString())) { 238 | excelData.add(rowData); 239 | } 240 | } 241 | return excelData; 242 | } catch (InvalidFormatException e) { 243 | throw new BaseException(FileUploadApiCode.INVALID_FORMAT); 244 | } catch (IOException e) { 245 | throw new BaseException(FileUploadApiCode.IO_EXCEPTION); 246 | } catch (MideaException e) { 247 | throw BusinessException.IMPORT_DATA_EXCEPTION.newInstance("数据大小超过限定大小:{0}行",1000); 248 | } 249 | } 250 | 251 | public static void main(String[] args) throws IOException { 252 | InputStream stream = new FileInputStream(new File("E:\\temp\\用户数据.xlsx")); 253 | List> data = readFromExcel(stream); 254 | System.out.println(FastJSONHelper.serialize(data)); 255 | } 256 | } 257 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/FTPUtil.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileWriter; 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | import java.io.InputStreamReader; 11 | import java.net.SocketException; 12 | 13 | import org.apache.commons.net.ftp.FTPClient; 14 | import org.apache.commons.net.ftp.FTPReply; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | 18 | /** 19 | * FTP工具类 20 | * 21 | * @author wujun10 22 | * 23 | */ 24 | public class FTPUtil { 25 | 26 | private static Logger logger = LoggerFactory.getLogger(FTPUtil.class); 27 | 28 | /** 29 | * 获取FTPClient对象 30 | * 31 | * @param ftpHost 32 | * FTP主机服务器 33 | * @param ftpPassword 34 | * FTP 登录密码 35 | * @param ftpUserName 36 | * FTP登录用户名 37 | * @param ftpPort 38 | * FTP端口 默认为21 39 | * @return 40 | */ 41 | public static FTPClient getFTPClient(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) { 42 | FTPClient ftpClient = null; 43 | try { 44 | ftpClient = new FTPClient(); 45 | ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器 46 | ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器 47 | if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { 48 | logger.info("未连接到FTP,用户名或密码错误。"); 49 | ftpClient.disconnect(); 50 | } else { 51 | logger.info("FTP连接成功。"); 52 | } 53 | } catch (SocketException e) { 54 | logger.info("FTP的IP地址可能错误,请正确配置。错误信息:[{}]", e); 55 | } catch (IOException e) { 56 | logger.info("FTP的端口错误,请正确配置。错误信息:[{}]", e); 57 | } 58 | return ftpClient; 59 | } 60 | 61 | /** 62 | * 去 服务器的FTP路径下上下载文件 63 | * 64 | * @param ftpHost 65 | * @param ftpPort 66 | * @param ftpUserName 67 | * @param ftpPassword 68 | * @param ftpPath 69 | * @param fileName 70 | * @param localPath 71 | * @return 72 | */ 73 | public static boolean downloadFileFromFTP(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String ftpPath, 74 | String fileName, String localPath) { 75 | boolean flag = false; 76 | StringBuffer resultBuffer = new StringBuffer(); 77 | InputStream in = null; 78 | FTPClient ftpClient = null; 79 | logger.info("开始读取绝对路径" + ftpPath + "文件!"); 80 | try { 81 | ftpClient = FTPUtil.getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword); 82 | ftpClient.setControlEncoding("UTF-8"); // 中文支持 83 | ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 84 | ftpClient.enterLocalPassiveMode(); 85 | ftpClient.changeWorkingDirectory(ftpPath); 86 | in = ftpClient.retrieveFileStream(fileName); 87 | } catch (FileNotFoundException e) { 88 | logger.error("没有找到" + ftpPath + "文件。错误信息:[{}]", e); 89 | } catch (SocketException e) { 90 | logger.error("连接FTP失败.错误信息:[{}]", e); 91 | } catch (IOException e) { 92 | logger.error("文件读取错误。错误信息:[{}]", e); 93 | } 94 | if (in != null) { 95 | FileWriter fileWriter = null; 96 | BufferedReader br = new BufferedReader(new InputStreamReader(in)); 97 | String data = null; 98 | try { 99 | fileWriter = new FileWriter(new File(localPath + File.separator + fileName)); 100 | while ((data = br.readLine()) != null) { 101 | resultBuffer.append(data + "\n"); 102 | } 103 | fileWriter.write(resultBuffer.toString()); 104 | fileWriter.flush(); 105 | fileWriter.close(); 106 | flag = true; 107 | } catch (IOException e) { 108 | logger.error("文件读取错误。错误信息:[{}]", e); 109 | } finally { 110 | try { 111 | ftpClient.disconnect(); 112 | } catch (IOException e) { 113 | e.printStackTrace(); 114 | } 115 | } 116 | } else { 117 | logger.error("in为空,不能读取。"); 118 | } 119 | return flag; 120 | } 121 | 122 | /** 123 | * 本地上传文件到FTP服务器 124 | * 125 | * @param ftpHost 126 | * @param ftpPort 127 | * @param ftpUserName 128 | * @param ftpPassword 129 | * @param ftpPath 130 | * @param fileName 131 | * @param localPath 132 | */ 133 | public static boolean uploadFileToFTP(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String ftpPath, 134 | String fileName, String localPath) { 135 | boolean flag = false; 136 | FTPClient ftpClient = null; 137 | logger.info("开始上传文件到FTP."); 138 | try { 139 | ftpClient = FTPUtil.getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword); 140 | // 设置PassiveMode传输 141 | ftpClient.enterLocalPassiveMode(); 142 | // 设置以二进制流的方式传输 143 | ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 144 | // 对远程目录的处理 145 | String remoteFileName = ftpPath; 146 | File f = new File(localPath + File.separator + fileName); 147 | InputStream in = new FileInputStream(f); 148 | ftpClient.storeFile(remoteFileName, in); 149 | in.close(); 150 | flag = true; 151 | logger.info("上传文件" + remoteFileName + "到FTP成功!"); 152 | } catch (Exception e) { 153 | logger.error("上传文件错误。错误信息:[{}]", e); 154 | } finally { 155 | try { 156 | ftpClient.disconnect(); 157 | } catch (IOException e) { 158 | e.printStackTrace(); 159 | } 160 | } 161 | return flag; 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/FastJSONHelper.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | import java.util.HashMap; 3 | import java.util.List; 4 | 5 | import com.alibaba.fastjson.JSON; 6 | import com.alibaba.fastjson.TypeReference; 7 | import com.alibaba.fastjson.serializer.SerializerFeature; 8 | 9 | public class FastJSONHelper { 10 | 11 | /** 12 | * 将java类型的对象转换为JSON格式的字符串 13 | * @param object java类型的对象 14 | * @return JSON格式的字符串 15 | */ 16 | public static String serialize(T object) { 17 | return JSON.toJSONString(object,SerializerFeature.WriteMapNullValue); 18 | } 19 | 20 | /** 21 | * 将java类型的对象转换为JSON格式的字符串, 可定制输出格式 22 | * @param object 23 | * @param serializerFeature 24 | * @return 25 | */ 26 | public static String serialize(T object, SerializerFeature serializerFeature) { 27 | return JSON.toJSONString(object, serializerFeature); 28 | } 29 | 30 | 31 | /** 32 | * 将JSON格式的字符串转换为java类型的对象或者java数组类型的对象,不包括java集合类型 33 | * @param json JSON格式的字符串 34 | * @param clz java类型或者java数组类型,不包括java集合类型 35 | * @return java类型的对象或者java数组类型的对象,不包括java集合类型的对象 36 | */ 37 | public static T deserialize(String json, Class clz) { 38 | return JSON.parseObject(json, clz); 39 | } 40 | 41 | /** 42 | * 将JSON格式的字符串转换为List类型的对象 43 | * @param json JSON格式的字符串 44 | * @param clz 指定泛型集合里面的T类型 45 | * @return List类型的对象 46 | */ 47 | public static List deserializeList(String json, Class clz) { 48 | return JSON.parseArray(json, clz); 49 | } 50 | 51 | /** 52 | * 将JSON格式的字符串转换成任意Java类型的对象 53 | * @param json JSON格式的字符串 54 | * @param type 任意Java类型 55 | * @return 任意Java类型的对象 56 | */ 57 | public static T deserializeAny(String json, TypeReference type) { 58 | return JSON.parseObject(json, type); 59 | } 60 | 61 | 62 | public static String getJsonValue(String json, String key){ 63 | HashMap map = FastJSONHelper.deserialize(json, HashMap.class); 64 | return (String)map.get(key); 65 | } 66 | 67 | } -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/JacksonMapper.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.io.IOException; 4 | import java.io.StringWriter; 5 | import java.lang.reflect.Array; 6 | import java.util.ArrayList; 7 | import java.util.Arrays; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | import org.apache.commons.lang.StringUtils; 12 | import org.codehaus.jackson.JsonFactory; 13 | import org.codehaus.jackson.JsonGenerationException; 14 | import org.codehaus.jackson.JsonGenerator; 15 | import org.codehaus.jackson.JsonParseException; 16 | import org.codehaus.jackson.map.DeserializationConfig; 17 | import org.codehaus.jackson.map.JsonMappingException; 18 | import org.codehaus.jackson.map.ObjectMapper; 19 | import org.codehaus.jackson.type.TypeReference; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | 23 | /** 24 | * 25 | * @ClassName: JacksonMapper 26 | * @Description: jackson json工具类 27 | * @author 汪海霖 wanghl15@midea.com.cn 28 | * @date 2014-5-24 上午1:15:31 29 | * 30 | */ 31 | public class JacksonMapper{ 32 | /** **/ 33 | private static final Logger logger = LoggerFactory.getLogger(JacksonMapper.class); 34 | 35 | private static JacksonMapper jacksonMapper = new JacksonMapper(); 36 | /**实例化工具类 **/ 37 | private ObjectMapper mapper; 38 | /**私有化构造方法**/ 39 | private JacksonMapper() { 40 | mapper = new ObjectMapper(); 41 | mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); 42 | } 43 | private static final int ARRAY_MAX = 1024; 44 | /** 45 | * 恶汉单例模式 46 | * @return 47 | */ 48 | public static ObjectMapper getInstance() { 49 | return jacksonMapper.mapper; 50 | } 51 | /** 52 | * json转化为java bean 53 | * @param json 54 | * @param valueType 55 | * @return 56 | */ 57 | public static T jsonToBean(String json, Class valueType){ 58 | if(StringUtils.isNotBlank(json)){ 59 | try { 60 | return getInstance().readValue(json, valueType); 61 | } catch (JsonParseException e) { 62 | logger.warn(e.getMessage(),e); 63 | } catch (JsonMappingException e) { 64 | logger.warn(e.getMessage(),e); 65 | } catch (IOException e) { 66 | logger.warn(e.getMessage(),e); 67 | } 68 | } 69 | return null; 70 | } 71 | /** 72 | * java bean转化为json 73 | * @param bean 74 | * @return 75 | */ 76 | public static String beanToJson(Object bean){ 77 | StringWriter sw = new StringWriter(); 78 | JsonGenerator gen = null; 79 | try { 80 | gen = new JsonFactory().createJsonGenerator(sw); 81 | getInstance().writeValue(gen, bean); 82 | gen.close(); 83 | } catch (IOException e) { 84 | logger.warn(e.getMessage(),e); 85 | } 86 | return sw.toString(); 87 | } 88 | 89 | /** 90 | * 91 | * 功能描述:
92 | * 〈功能详细描述〉 93 | * @param 94 | * 95 | * @param json 96 | * @param type 97 | * @return 98 | * @throws IOException 99 | * @throws JsonMappingException 100 | * @throws JsonParseException 101 | * @see [相关类/方法](可选) 102 | * @since [产品/模块版本](可选) 103 | */ 104 | @SuppressWarnings("unchecked") 105 | public static List jsonToList(String json,Class clazz) { 106 | if(StringUtils.isNotBlank(json)){ 107 | T[] t = (T[]) Array.newInstance(clazz, ARRAY_MAX); 108 | try { 109 | t = (T[]) getInstance().readValue(json, t.getClass()); 110 | List list = (List) Arrays.asList(t); 111 | return list; 112 | } catch (JsonGenerationException e) { 113 | logger.error(e.getMessage()); 114 | } catch (JsonMappingException e) { 115 | logger.error(e.getMessage()); 116 | } catch (IOException e) { 117 | logger.error(e.getMessage()); 118 | } 119 | } 120 | return null; 121 | } 122 | 123 | public static List json2list(String jsonArrayStr, Class clazz) 124 | throws Exception { 125 | List> list = getInstance().readValue(jsonArrayStr, 126 | new TypeReference>() { 127 | }); 128 | List result = new ArrayList(); 129 | for (Map map : list) { 130 | result.add(map2pojo(map, clazz)); 131 | } 132 | return result; 133 | } 134 | 135 | @SuppressWarnings("rawtypes") 136 | public static T map2pojo(Map map, Class clazz) { 137 | return getInstance().convertValue(map, clazz); 138 | } 139 | 140 | /** 141 | * 142 | * 功能描述:
143 | * 〈功能详细描述〉 144 | * 145 | * @param t 146 | * @return 147 | * @see [相关类/方法](可选) 148 | * @since [产品/模块版本](可选) 149 | */ 150 | public static String listToJson(List t){ 151 | try { 152 | return getInstance().writeValueAsString(t); 153 | } catch (JsonGenerationException e) { 154 | logger.error(e.getMessage()); 155 | } catch (JsonMappingException e) { 156 | logger.error(e.getMessage()); 157 | } catch (IOException e) { 158 | logger.error(e.getMessage()); 159 | } 160 | return null; 161 | } 162 | 163 | 164 | } 165 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/MathUtils.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.math.BigDecimal; 4 | import java.text.DecimalFormat; 5 | /** 6 | * 运算类工具类 7 | * @author liuzhihong 8 | * @date 2017年4月11日 下午2:10:39 9 | */ 10 | public class MathUtils { 11 | 12 | public static final int SCALE = 2; 13 | public static final int PERCENTAGE_SCALE = 4; 14 | 15 | /** 16 | * 按四舍五入法获得2位小数的商 17 | * @param dividend 18 | * @param divisor 19 | * @return 20 | */ 21 | public static double getQuotient4down5up(Number dividend,Number divisor) { 22 | double quotient = 0.00; 23 | if (dividend != null && divisor != null && divisor.doubleValue() != 0.0){ 24 | quotient = new BigDecimal(dividend.doubleValue()) 25 | .divide(new BigDecimal(divisor.doubleValue()),SCALE,BigDecimal.ROUND_HALF_UP) 26 | .doubleValue(); 27 | } 28 | return quotient; 29 | } 30 | 31 | /** 32 | * 按四舍五入法获得指定位小数的商 33 | * @param dividend 34 | * @param divisor 35 | * @return 36 | */ 37 | public static double getQuotient4down5up(Number dividend,Number divisor,int specificScale) { 38 | double quotient = 0.00; 39 | if (divisor.doubleValue() != 0.0 && dividend != null){ 40 | quotient = new BigDecimal(dividend.doubleValue()) 41 | .divide(new BigDecimal(divisor.doubleValue()),specificScale,BigDecimal.ROUND_HALF_UP) 42 | .doubleValue(); 43 | } 44 | return quotient; 45 | } 46 | 47 | /** 48 | * 按四舍五入法获得2位小数的商,并转化为百分数,且保留两位小数 49 | * @param dividend 50 | * @param divisor 51 | * @return 52 | */ 53 | public static String getPercentage4down5up(Number dividend,Number divisor) { 54 | double quotient = 0.00; 55 | if (divisor.doubleValue() != 0.0){ 56 | quotient = new BigDecimal(dividend.doubleValue()) 57 | .divide(new BigDecimal(divisor.doubleValue()),PERCENTAGE_SCALE,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)) 58 | .doubleValue() ; 59 | } 60 | return formatDouble(quotient,2) + "%"; 61 | } 62 | 63 | public static String getPercentageFromDecimal4down5up(double decimal) { 64 | double approximation = new java.math.BigDecimal(Double.toString(decimal)).multiply(new BigDecimal(100)).setScale(SCALE,BigDecimal.ROUND_HALF_UP).doubleValue(); 65 | return formatDouble(approximation,2) + "%"; 66 | } 67 | 68 | public static String getPercentageFromDecimal4down5up(double decimal,int decimalCount) { 69 | double approximation = new java.math.BigDecimal(Double.toString(decimal)).multiply(new BigDecimal(100)).setScale(decimalCount,BigDecimal.ROUND_HALF_UP).doubleValue(); 70 | return formatDouble(approximation,decimalCount) + "%"; 71 | } 72 | 73 | /** 74 | * 75 | * @param decimal 76 | * @return 保留 ${decimalCount}位小数 77 | */ 78 | public static String formatDouble(double decimal,int decimalCount) { 79 | StringBuilder sb = new StringBuilder("#####0."); 80 | for (int i = 0; i < decimalCount; i++) { 81 | sb.append("0"); 82 | } 83 | DecimalFormat df = new DecimalFormat(sb.toString()); 84 | df.format(new BigDecimal(0.00)); 85 | return df.format(decimal); 86 | } 87 | 88 | /** 89 | * 90 | * @param decimal 91 | * @return 保留两位小数 92 | */ 93 | public static String formatDouble00(BigDecimal decimal) { 94 | DecimalFormat df = new DecimalFormat("#####0.00"); 95 | return df.format(decimal); 96 | } 97 | 98 | public static BigDecimal sum(BigDecimal augend1,BigDecimal augend2) { 99 | if (augend1 != null && augend2 != null) { 100 | return augend1.add(augend2); 101 | } else { 102 | return augend1 != null ? augend1:augend2; 103 | } 104 | } 105 | 106 | public static long sum(Long augend1,Long augend2) { 107 | if (augend1 != null && augend2 != null) { 108 | return augend1.longValue() + augend2.longValue(); 109 | } else { 110 | return augend1 != null ? augend1.longValue():augend2.longValue(); 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/Md5Util.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.security.MessageDigest; 4 | 5 | import org.apache.commons.codec.binary.Hex; 6 | /** 7 | * md5加密 8 | * @author xianqun.li 2016年1月15日 9 | * 10 | */ 11 | public class Md5Util { 12 | /** 13 | * md5运算 14 | * @param buf 15 | * @return 16 | */ 17 | public static byte[] md5(byte []buf) { 18 | try { 19 | MessageDigest md = MessageDigest.getInstance("MD5"); 20 | return md.digest(buf); 21 | } catch (Exception e) { 22 | throw new RuntimeException(e); 23 | } 24 | } 25 | 26 | /** 27 | * md5运算 28 | * @param buf 29 | * @return 30 | */ 31 | public static String md5String(byte []buf) { 32 | byte []tmp=md5(buf); 33 | return Hex.encodeHexString(tmp); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/NamedThreadFactory.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.util.concurrent.ThreadFactory; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | public class NamedThreadFactory implements ThreadFactory 7 | { 8 | private static final AtomicInteger POOL_SEQ = new AtomicInteger(1); 9 | 10 | private final AtomicInteger mThreadNum = new AtomicInteger(1); 11 | 12 | private final String mPrefix; 13 | 14 | private final boolean mDaemo; 15 | 16 | private final ThreadGroup mGroup; 17 | 18 | public NamedThreadFactory() 19 | { 20 | this("pool-" + POOL_SEQ.getAndIncrement(),false); 21 | } 22 | 23 | public NamedThreadFactory(String prefix) 24 | { 25 | this(prefix,false); 26 | } 27 | 28 | public NamedThreadFactory(String prefix,boolean daemo) 29 | { 30 | mPrefix = prefix + "-thread-"; 31 | mDaemo = daemo; 32 | SecurityManager s = System.getSecurityManager(); 33 | mGroup = ( s == null ) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup(); 34 | } 35 | 36 | public Thread newThread(Runnable runnable) 37 | { 38 | String name = mPrefix + mThreadNum.getAndIncrement(); 39 | Thread ret = new Thread(mGroup,runnable,name,0); 40 | ret.setDaemon(mDaemo); 41 | return ret; 42 | } 43 | 44 | public ThreadGroup getThreadGroup() 45 | { 46 | return mGroup; 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/RedisLockUtil.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.util.Random; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | /** 9 | * 10 | * @ClassName: RedisLockUtil 11 | * @Description: redis锁实现类 12 | * @author 汪海霖 wanghl15@midea.com.cn 13 | * @date 2014-9-2 下午11:00:46 14 | */ 15 | public class RedisLockUtil { 16 | 17 | /**加锁标志 **/ 18 | public static final String LOCKED = "TRUE"; 19 | /**锁的超时时间(秒),过期删除 **/ 20 | public static final int EXPIRE = 180; 21 | /**1毫秒对应的纳秒时间**/ 22 | public static final long ONE_MILLI_NANOS = 1000000L; 23 | /**默认超时时间(毫秒) **/ 24 | public static final long DEFAULT_TIME_OUT = 2000; 25 | /**随机数**/ 26 | public static final Random random = new Random(); 27 | 28 | private static Logger logger = LoggerFactory.getLogger(RedisLockUtil.class); 29 | 30 | /** 31 | * 加锁 保证原子性 32 | * @param operateLogic 处理逻辑 33 | * @param lockCacheKey 锁的cache key 34 | * @param timeOut 毫秒数 获取锁的超时时间 35 | * @return 36 | * @throws Exception 37 | */ 38 | public static T executeSynchOperate(MainOperator operator, 39 | String lockCacheKey,long milliTimeout) throws Exception{ 40 | Boolean locked = false; 41 | long startNaros = System.nanoTime(); 42 | long nanoTimeOut = milliTimeout*1000000L; 43 | T resultObj = null; 44 | try{ 45 | while(System.nanoTime()-startNaros < nanoTimeOut){ 46 | if(JedisUtil.getJedisInstance().execSetnxToCache(lockCacheKey, LOCKED) == 1){ 47 | JedisUtil.getJedisInstance().execExpireToCache(lockCacheKey, EXPIRE); 48 | locked = true; 49 | break; 50 | } 51 | Thread.sleep(30,random.nextInt(500)); 52 | } 53 | resultObj = operator.executeInvokeLogic(locked); 54 | }catch(Exception ex){ 55 | throw ex; 56 | }finally{ 57 | if (locked) { 58 | releaseRedisLock(lockCacheKey); 59 | } 60 | } 61 | return resultObj; 62 | } 63 | 64 | /** 65 | * 操作本身实现的逻辑 66 | * @param 67 | */ 68 | public abstract interface MainOperator{ 69 | public abstract T executeInvokeLogic (boolean result)throws Exception; 70 | } 71 | 72 | /** 73 | * 释放锁 74 | * @param cacheKey 75 | */ 76 | public static void releaseRedisLock(final String cacheKey){ 77 | JedisUtil.getJedisInstance().execDelToCache(cacheKey); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/ReflectionUtils.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.lang.reflect.Field; 4 | import java.lang.reflect.Modifier; 5 | import java.lang.reflect.ParameterizedType; 6 | import java.lang.reflect.Type; 7 | import java.util.ArrayList; 8 | import java.util.Collection; 9 | import java.util.List; 10 | 11 | import org.apache.commons.beanutils.PropertyUtils; 12 | import org.apache.commons.lang.StringUtils; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | import org.springframework.util.Assert; 16 | 17 | public class ReflectionUtils { 18 | 19 | private static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class); 20 | 21 | /** 22 | * 直接读取对象属性值,无视private/protected修饰符,不经过getter函数. 23 | */ 24 | public static Object getFieldValue(final Object object, final String fieldName) { 25 | Field field = getDeclaredField(object, fieldName); 26 | 27 | if (field == null) 28 | throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]"); 29 | 30 | makeAccessible(field); 31 | 32 | Object result = null; 33 | try { 34 | result = field.get(object); 35 | } catch (IllegalAccessException e) { 36 | logger.error("不可能抛出的异常{}", e.getMessage()); 37 | } 38 | return result; 39 | } 40 | 41 | /** 42 | * 直接设置对象属性值,无视private/protected修饰符,不经过setter函数. 43 | */ 44 | public static void setFieldValue(final Object object, final String fieldName, final Object value) { 45 | Field field = getDeclaredField(object, fieldName); 46 | 47 | if (field == null) 48 | throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]"); 49 | 50 | makeAccessible(field); 51 | 52 | try { 53 | field.set(object, value); 54 | } catch (IllegalAccessException e) { 55 | logger.error("不可能抛出的异常:{}", e.getMessage()); 56 | } 57 | } 58 | 59 | /** 60 | * 循环向上转型,获取对象的DeclaredField. 61 | */ 62 | public static Field getDeclaredField(final Object object, final String fieldName) { 63 | Assert.notNull(object, "object不能为空"); 64 | return getDeclaredField(object.getClass(), fieldName); 65 | } 66 | 67 | /** 68 | * 循环向上转型,获取类的DeclaredField. 69 | */ 70 | @SuppressWarnings("unchecked") 71 | protected static Field getDeclaredField(final Class clazz, final String fieldName) { 72 | Assert.notNull(clazz, "clazz不能为空"); 73 | Assert.hasText(fieldName, "fieldName"); 74 | for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) { 75 | try { 76 | return superClass.getDeclaredField(fieldName); 77 | } catch (NoSuchFieldException e) { 78 | // Field不在当前类定义,继续向上转型 79 | } 80 | } 81 | return null; 82 | } 83 | 84 | /** 85 | * 强制转换fileld可访问. 86 | */ 87 | protected static void makeAccessible(final Field field) { 88 | if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) { 89 | field.setAccessible(true); 90 | } 91 | } 92 | 93 | /** 94 | * 通过反射,获得定义Class时声明的父类的泛型参数的类型. 如public UserDao extends HibernateDao 95 | * 96 | * @param clazz 97 | * The class to introspect 98 | * @return the first generic declaration, or Object.class if cannot be 99 | * determined 100 | */ 101 | @SuppressWarnings("unchecked") 102 | public static Class getSuperClassGenricType(final Class clazz) { 103 | return getSuperClassGenricType(clazz, 0); 104 | } 105 | 106 | /** 107 | * 通过反射,获得定义Class时声明的父类的泛型参数的类型. 如public UserDao extends HibernateDao 108 | * 109 | * 110 | * @param clazz 111 | * clazz The class to introspect 112 | * @param index 113 | * the Index of the generic ddeclaration,start from 0. 114 | * @return the index generic declaration, or Object.class if cannot be 115 | * determined 116 | */ 117 | 118 | @SuppressWarnings("unchecked") 119 | public static Class getSuperClassGenricType(final Class clazz, final int index) { 120 | 121 | Type genType = clazz.getGenericSuperclass(); 122 | 123 | if (!(genType instanceof ParameterizedType)) { 124 | logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType"); 125 | return Object.class; 126 | } 127 | 128 | Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); 129 | 130 | if (index >= params.length || index < 0) { 131 | logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " 132 | + params.length); 133 | return Object.class; 134 | } 135 | if (!(params[index] instanceof Class)) { 136 | logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); 137 | return Object.class; 138 | } 139 | return (Class) params[index]; 140 | } 141 | 142 | /** 143 | * 提取集合中的对象的属性,组合成List. 144 | * 145 | * @param collection 146 | * 来源集合. 147 | * @param propertityName 148 | * 要提取的属性名. 149 | */ 150 | @SuppressWarnings("unchecked") 151 | public static List fetchElementPropertyToList(final Collection collection, final String propertyName) 152 | throws Exception { 153 | 154 | List list = new ArrayList(); 155 | 156 | for (Object obj : collection) { 157 | list.add(PropertyUtils.getProperty(obj, propertyName)); 158 | } 159 | 160 | return list; 161 | } 162 | 163 | /** 164 | * 提取集合中的对象的属性,组合成由分割符分隔的字符串. 165 | * 166 | * @param collection 167 | * 来源集合. 168 | * @param propertityName 169 | * 要提取的属性名. 170 | * @param separator 171 | * 分隔符. 172 | */ 173 | @SuppressWarnings("unchecked") 174 | public static String fetchElementPropertyToString(final Collection collection, final String propertyName, 175 | final String separator) throws Exception { 176 | List list = fetchElementPropertyToList(collection, propertyName); 177 | return StringUtils.join(list.toArray(), separator); 178 | } 179 | 180 | } 181 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/RespPackUtil.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.net.ConnectException; 4 | import java.net.SocketTimeoutException; 5 | 6 | import org.apache.commons.lang.StringUtils; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import com.alibaba.dubbo.remoting.TimeoutException; 11 | import com.liu.code.BaseApiCode; 12 | import com.liu.core.ServiceWrapper; 13 | import com.liu.request.BaseRequest; 14 | import com.liu.response.BaseResponse; 15 | /** 16 | * @ClassName: RespPackUtil 17 | * @Description: 响应包装类 18 | * @author 汪海霖 wanghl15@midea.com.cn 19 | * @date 2014-10-2 上午9:53:31 20 | */ 21 | public class RespPackUtil { 22 | 23 | private final static Logger logger = LoggerFactory.getLogger(RespPackUtil.class); 24 | 25 | // private static MessageProducer messageProducer; 26 | 27 | /** 28 | * @Title: execInvokeService 29 | * @Description: 统一包装调用后端服务 30 | * @return CoreResponse 返回类型 31 | * @throws 32 | */ 33 | public static BaseResponse execInvokeService(BaseRequest request, BaseResponse response,ServiceWrapper wrapper) { 34 | StringBuilder strBuff = new StringBuilder(); 35 | long startTime = System.currentTimeMillis(); 36 | StackTraceElement ste = new Exception().getStackTrace()[1]; 37 | //服务方法名 38 | String methodName = ste.getMethodName(); 39 | //服务类名 40 | String serviceName = StringUtils.substringBefore(getSimpleClassName(ste.getClassName()), "Impl"); 41 | String facadeName = serviceName.concat(".").concat(methodName); 42 | String reqStr = FastJSONHelper.serialize(request); 43 | String reqLogStr = StringUtils.isBlank(wrapper.getTraceId()) ? reqStr : wrapper.getTraceId(); 44 | strBuff.append("调用服务==").append(facadeName).append(";请求数据==").append(reqLogStr).append(";"); 45 | //数据检查 46 | String checkResult = request.check(); 47 | String resultCode = null; 48 | Exception ex = null; 49 | if (StringUtils.isBlank(checkResult)) { 50 | try{ 51 | //调用服务 52 | resultCode = wrapper.invokeService(); 53 | }catch(Exception e){//服务异常 54 | ex = e; 55 | resultCode = BaseApiCode.OPERATE_SYSTEM_FAIL; 56 | //异常预警 57 | //execInvokeFailToNotice(serviceName, methodName, ex, reqStr); 58 | } 59 | } else {//参数缺失 60 | resultCode = BaseApiCode.OPERATE_PARAM_INVALID; 61 | strBuff.append("检测到数据错误描述==").append(checkResult).append(";"); 62 | } 63 | //包装response 64 | packBaseResponse(response, resultCode, checkResult); 65 | String respStr = FastJSONHelper.serialize(response); 66 | if(wrapper.isNoticeInvokeFail(response)){//调用失败是否通知 67 | //故障报警 68 | // StringBuilder faultCodeBuff = new StringBuilder(facadeName); 69 | // faultCodeBuff.append("||").append(response.getEnMsg()); 70 | // sendNoticeToMq(faultCodeBuff.toString(), reqStr, respStr); 71 | } 72 | strBuff.append("resultCode==").append(resultCode) 73 | .append(";共耗时==").append(System.currentTimeMillis()-startTime) 74 | .append(";response==").append(respStr).append(";"); 75 | if(BaseApiCode.OPERATE_SUCCESS.equals(resultCode)){ 76 | Boolean sendResult = wrapper.sendChangeNotify(); 77 | if(sendResult != null){ 78 | strBuff.append("单据内容变更通知消息发送完成,notifyMqSendResult==").append(sendResult).append(";"); 79 | } 80 | } 81 | if(StringUtils.equals(BaseApiCode.OPERATE_SUCCESS, resultCode)){//调用成功 82 | //服务成功但调用时间过长 83 | if(wrapper.isMonitorSuccess() || System.currentTimeMillis() - startTime > wrapper.timeout()){ 84 | logger.info(strBuff.toString()); 85 | }else{ 86 | logger.debug(strBuff.toString()); 87 | } 88 | }else{ //是否监控+是否忽略失败的操作 89 | if(ex != null){//服务异常 90 | strBuff.append(";error_msg=="); 91 | Throwable cause = ex.getCause(); 92 | if(isTimeoutThrowable(cause)){ //超时异常 93 | strBuff.append(cause.getMessage()); 94 | logger.error(strBuff.toString()); 95 | }else{ 96 | strBuff.append(ex.getMessage()); 97 | logger.error(strBuff.toString(), ex); 98 | } 99 | }else{ 100 | logger.info(strBuff.toString()); 101 | } 102 | } 103 | return response; 104 | } 105 | 106 | //包装Response 107 | private static void packBaseResponse(BaseResponse response, String resultCode, String errorDetail) { 108 | if (!BaseApiCode.OPERATE_SUCCESS.equals(resultCode)) { 109 | response.setErrorCode(resultCode); 110 | } 111 | response.setEnMsg(BaseApiCode.getEnMsg(resultCode)); 112 | response.setZhMsg(BaseApiCode.getZhMsg(resultCode)); 113 | if (StringUtils.isNotBlank(errorDetail)) { 114 | response.setZhDetailMsg(errorDetail); 115 | } 116 | } 117 | 118 | //判断是否超时或者网络方面的异常 119 | public static boolean isTimeoutThrowable(Throwable cause){ 120 | if(cause != null && (cause instanceof TimeoutException 121 | || cause instanceof SocketTimeoutException 122 | || cause instanceof ConnectException)){ 123 | return true; 124 | }else{ 125 | return false; 126 | } 127 | } 128 | 129 | //是否打印debug日志 130 | public static boolean isPrintDebugLog(String facadeName){ 131 | return false; 132 | } 133 | 134 | private static String getSimpleClassName(String className){ 135 | return className.substring(className.lastIndexOf(".")+1); 136 | } 137 | 138 | //服务失败通知策略 139 | /*public static void execInvokeFailToNotice(String serviceName,String methodName, 140 | Exception ex,String reqStr){ 141 | //获取当前时间的月日时MMddHH 142 | String mdh = DateTool.getDateToMDH(DateTool.getCurrentDate()); 143 | //异常名 如:NullPointerException 144 | String exName = ex.getClass().getSimpleName(); 145 | //异常通知cache key(时间+服务名+异常名) 146 | String noticeKey = mdh+methodName+exName; 147 | //故障编码 148 | String faultCode = serviceName+"."+methodName; 149 | //计算同一服务同一类型异常次数 150 | Long incrNum = JedisUtil.getJedisInstance().execIncrToCache(noticeKey); 151 | if(incrNum == Constants.CONSTANT_ONE_INT){//首次异常设置cache作废时间 152 | JedisUtil.getJedisInstance().execExpireToCache(noticeKey, Constants.REDIS_ONEDAY); 153 | } 154 | StringBuilder errorBuff = new StringBuilder("调用服务:"); 155 | errorBuff.append(faultCode).append("异常,错误信息:") 156 | .append(ex.getClass().getName()).append(":"); 157 | Throwable cause = ex.getCause(); 158 | if(isTimeoutThrowable(cause)){//超时异常 159 | errorBuff.append(cause.getMessage()); 160 | }else{//后期可以给异常分类 161 | errorBuff.append(ex.getMessage()); 162 | } 163 | if(incrNum % 100 == Constants.CONSTANT_ONE_INT){//每累计一百次发送通知 164 | sendNoticeToMq(faultCode,reqStr,errorBuff.toString()); 165 | } 166 | }*/ 167 | 168 | //发送报障邮件数据到MQ 169 | /*public static boolean sendNoticeToMq(String faultCode,String reqStr,String errorStr){ 170 | FaultReportRequest reportRequest = new FaultReportRequest(); 171 | reportRequest.setFaultMsg(errorStr); 172 | reportRequest.setReqParam(reqStr); 173 | reportRequest.setResParam(errorStr); 174 | reportRequest.setFaultTime(DateTool.getCurrentDate()); 175 | reportRequest.setFaultCode(faultCode); 176 | reportRequest.setReporter("系统"); 177 | if(messageProducer == null){ 178 | messageProducer = AppSpringContext.getBean("messageProducer", MessageProducer.class); 179 | } 180 | return messageProducer.sendMessage(MqSendType.SERVICE_FAIL_NOTICE, 181 | String.valueOf(System.currentTimeMillis()).concat(RandomStringUtils.randomNumeric(5)), 182 | JacksonMapper.beanToJson(reportRequest)); 183 | }*/ 184 | 185 | 186 | } 187 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/RetryHelper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.liu.utils; 5 | 6 | import com.liu.Constants; 7 | import com.liu.exceptions.TradeSystemException; 8 | 9 | /** 10 | * @ClassName: RetryHelper 11 | * @Description: 重试类 12 | * @author 汪海霖 wanghl15@midea.com.cn 13 | * @date 2014-9-21 下午1:25:30 14 | */ 15 | public class RetryHelper { 16 | 17 | //指定异常的重试 如超时 18 | public static T retryExecute(RetryWrapper operator,int retryNum){ 19 | for(int index = retryNum -1 ;index >= 0; index-- ){ 20 | if(index == Constants.CONSTANT_ZERO_INT){ 21 | return operator.invoke(); 22 | }else{ 23 | try{ 24 | return operator.invoke(); 25 | }catch(Exception ex){ 26 | if(!operator.retryStrategy(ex)){ 27 | throw new TradeSystemException(ex); 28 | } 29 | } 30 | } 31 | } 32 | return null; 33 | } 34 | 35 | //控制重试次数 36 | public static void holdRetryNum(RetryWrapper operator,int retryNum){ 37 | Long cacheNum = JedisUtil.getJedisInstance().execIncrToCache(operator.getCacheKey()); 38 | JedisUtil.getJedisInstance().execExpireToCache(operator.getCacheKey(), operator.getExpireTime()); 39 | if(cacheNum <= retryNum){ 40 | operator.invoke(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/RetryWrapper.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import com.liu.Constants; 4 | 5 | /** 6 | * 7 | * @ClassName: RetryWrapper 8 | * @Description: 重试包装类 9 | * @author 汪海霖 wanghl15@midea.com.cn 10 | * @date 2015-4-23 下午2:01:18 11 | */ 12 | 13 | public abstract class RetryWrapper{ 14 | 15 | //调用方法 16 | public abstract T invoke(); 17 | 18 | //是否重试策略 19 | public boolean retryStrategy(Exception ex){ 20 | Throwable cause = ex.getCause(); 21 | return RespPackUtil.isTimeoutThrowable(cause); 22 | } 23 | 24 | //控制重试次数key 25 | public String getCacheKey(){ 26 | return null; 27 | } 28 | 29 | //期满时间 30 | public int getExpireTime(){ 31 | return Constants.REDIS_ONEDAY; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/SFTPUtil.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | import java.util.Properties; 9 | 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | import com.jcraft.jsch.Channel; 14 | import com.jcraft.jsch.ChannelSftp; 15 | import com.jcraft.jsch.JSch; 16 | import com.jcraft.jsch.Session; 17 | import com.jcraft.jsch.SftpATTRS; 18 | import com.jcraft.jsch.SftpException; 19 | 20 | public class SFTPUtil { 21 | 22 | private static Logger logger = LoggerFactory.getLogger(SFTPUtil.class); 23 | 24 | public static String OPERATE_UPLOAD = "upload"; 25 | public static String OPERATE_DOWNLOAD = "download"; 26 | 27 | private String host;// 服务器连接ip 28 | private int port;// 端口号 29 | private String username;// 用户名 30 | private String password;// 密码 31 | 32 | private ChannelSftp sftp = null; 33 | private Session sshSession = null; 34 | 35 | public SFTPUtil(String host, int port, String username, String password) { 36 | this.host = host; 37 | this.port = port; 38 | this.username = username; 39 | this.password = password; 40 | } 41 | 42 | /** 43 | * 通过SFTP连接服务器 44 | */ 45 | public void connect() { 46 | try { 47 | JSch jsch = new JSch(); 48 | jsch.getSession(username, host, port); 49 | sshSession = jsch.getSession(username, host, port); 50 | if (logger.isInfoEnabled()) { 51 | logger.info("Session created."); 52 | } 53 | sshSession.setPassword(password); 54 | Properties sshConfig = new Properties(); 55 | sshConfig.put("StrictHostKeyChecking", "no"); 56 | sshSession.setConfig(sshConfig); 57 | sshSession.connect(); 58 | if (logger.isInfoEnabled()) { 59 | logger.info("Session connected."); 60 | } 61 | Channel channel = sshSession.openChannel("sftp"); 62 | channel.connect(); 63 | if (logger.isInfoEnabled()) { 64 | logger.info("Opening Channel."); 65 | } 66 | sftp = (ChannelSftp) channel; 67 | if (logger.isInfoEnabled()) { 68 | logger.info("Connected to " + host + "."); 69 | } 70 | } catch (Exception e) { 71 | e.printStackTrace(); 72 | } 73 | } 74 | 75 | /** 76 | * 关闭连接 77 | */ 78 | public void disconnect() { 79 | if (this.sftp != null) { 80 | if (this.sftp.isConnected()) { 81 | this.sftp.disconnect(); 82 | if (logger.isInfoEnabled()) { 83 | logger.info("sftp is closed already"); 84 | } 85 | } 86 | } 87 | if (this.sshSession != null) { 88 | if (this.sshSession.isConnected()) { 89 | this.sshSession.disconnect(); 90 | if (logger.isInfoEnabled()) { 91 | logger.info("sshSession is closed already"); 92 | } 93 | } 94 | } 95 | } 96 | 97 | /** 98 | * 下载单个文件 99 | * 100 | * @param remotPath:远程下载目录(以路径符号结束) 101 | * @param remoteFileName:下载文件名 102 | * @param localPath:本地保存目录(以路径符号结束) 103 | * @param localFileName:保存文件名 104 | * @return 105 | */ 106 | public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) { 107 | FileOutputStream fieloutput = null; 108 | try { 109 | File file = new File(localPath + localFileName); 110 | fieloutput = new FileOutputStream(file); 111 | sftp.get(remotePath + remoteFileName, fieloutput); 112 | if (logger.isInfoEnabled()) { 113 | logger.info("===DownloadFile:" + remoteFileName + " success from sftp."); 114 | } 115 | return true; 116 | } catch (FileNotFoundException e) { 117 | e.printStackTrace(); 118 | } catch (SftpException e) { 119 | e.printStackTrace(); 120 | } finally { 121 | if (null != fieloutput) { 122 | try { 123 | fieloutput.close(); 124 | } catch (IOException e) { 125 | e.printStackTrace(); 126 | } 127 | } 128 | } 129 | return false; 130 | } 131 | 132 | /** 133 | * 上传单个文件 134 | * 135 | * @param remotePath:远程保存目录 136 | * @param remoteFileName:保存文件名 137 | * @param localPath:本地上传目录(以路径符号结束) 138 | * @param localFileName:上传的文件名 139 | * @return 140 | */ 141 | public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName) { 142 | FileInputStream in = null; 143 | String tempRemoteFileName = remoteFileName + ".temp" ; 144 | try { 145 | createDir(remotePath); 146 | File file = new File(localPath + localFileName); 147 | in = new FileInputStream(file); 148 | sftp.put(in, tempRemoteFileName); 149 | sftp.rename(remotePath + tempRemoteFileName, remotePath + remoteFileName); 150 | return true; 151 | } catch (FileNotFoundException e) { 152 | e.printStackTrace(); 153 | } catch (SftpException e) { 154 | e.printStackTrace(); 155 | } finally { 156 | if (in != null) { 157 | try { 158 | in.close(); 159 | } catch (IOException e) { 160 | e.printStackTrace(); 161 | } 162 | } 163 | } 164 | return false; 165 | } 166 | 167 | /** 168 | * 创建目录 169 | * 170 | * @param createpath 171 | * @return 172 | */ 173 | public boolean createDir(String createpath) { 174 | try { 175 | if (isDirExist(createpath)) { 176 | this.sftp.cd(createpath); 177 | return true; 178 | } 179 | String pathArry[] = createpath.split("/"); 180 | StringBuffer filePath = new StringBuffer("/"); 181 | for (String path : pathArry) { 182 | if (path.equals("")) { 183 | continue; 184 | } 185 | filePath.append(path + "/"); 186 | if (isDirExist(filePath.toString())) { 187 | sftp.cd(filePath.toString()); 188 | } else { 189 | // 建立目录 190 | sftp.mkdir(filePath.toString()); 191 | // 进入并设置为当前目录 192 | sftp.cd(filePath.toString()); 193 | } 194 | 195 | } 196 | this.sftp.cd(createpath); 197 | return true; 198 | } catch (SftpException e) { 199 | e.printStackTrace(); 200 | } 201 | return false; 202 | } 203 | 204 | /** 205 | * 判断目录是否存在 206 | * 207 | * @param directory 208 | * @return 209 | */ 210 | public boolean isDirExist(String directory) { 211 | boolean isDirExistFlag = false; 212 | try { 213 | SftpATTRS sftpATTRS = sftp.lstat(directory); 214 | isDirExistFlag = true; 215 | return sftpATTRS.isDir(); 216 | } catch (Exception e) { 217 | if (e.getMessage().toLowerCase().equals("no such file")) { 218 | isDirExistFlag = false; 219 | } 220 | } 221 | return isDirExistFlag; 222 | } 223 | 224 | public boolean operateSFTP(String remotePath, String remoteFileName, String localPath, String localFileName, String operateType){ 225 | SFTPUtil sftp = null; 226 | try { 227 | sftp = new SFTPUtil(this.host, this.port, this.username, this.password); 228 | sftp.connect(); 229 | if(OPERATE_UPLOAD.equals(operateType)){ 230 | return sftp.uploadFile(remotePath, remoteFileName, localPath, localFileName); 231 | }else if(OPERATE_DOWNLOAD.equals(operateType)){ 232 | return sftp.downloadFile(remotePath, remoteFileName, localPath, localFileName); 233 | }else{ 234 | logger.info("操作类型不在已知的范围内"); 235 | } 236 | } catch (Exception e) { 237 | e.printStackTrace(); 238 | } finally { 239 | sftp.disconnect(); 240 | } 241 | return false; 242 | } 243 | 244 | } 245 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/ThreadPoolManager.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | import java.util.concurrent.Callable; 5 | import java.util.concurrent.CancellationException; 6 | import java.util.concurrent.ExecutionException; 7 | import java.util.concurrent.Executors; 8 | import java.util.concurrent.Future; 9 | import java.util.concurrent.RejectedExecutionHandler; 10 | import java.util.concurrent.ScheduledExecutorService; 11 | import java.util.concurrent.ThreadPoolExecutor; 12 | import java.util.concurrent.TimeUnit; 13 | 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | 17 | /** 18 | * 19 | * @ClassName: ThreadPoolManager 20 | * @Description: 线程池工具类 21 | * @author 汪海霖 wanghl15@midea.com.cn 22 | * @date 2014-5-24 上午10:17:42 23 | * 24 | */ 25 | public class ThreadPoolManager { 26 | 27 | private static Logger logger = LoggerFactory.getLogger(ThreadPoolManager.class); 28 | /** **/ 29 | private ThreadPoolExecutor threadPool; 30 | /** **/ 31 | private ArrayBlockingQueue taskQueue = new ArrayBlockingQueue(10000); 32 | /**核心线程个数**/ 33 | private static int corePoolSize = Runtime.getRuntime().availableProcessors()*2; 34 | /**最大线程个数 **/ 35 | private static int maximumPoolSize = Runtime.getRuntime().availableProcessors()*5; 36 | /**保持心跳时间 **/ 37 | private static int keepAliveTime = 1; 38 | /**定时执行线程个数**/ 39 | private final static int minSchedule = 2; 40 | /**线程池实例化**/ 41 | private static ThreadPoolManager threadPoolManage = new ThreadPoolManager(); 42 | /**延时执行线程**/ 43 | private ScheduledExecutorService appSchedule; 44 | /** 45 | * 线程池构造方法 46 | */ 47 | private ThreadPoolManager(){ 48 | RejectedExecutionHandler myHandler = new RejectedExecutionHandler(){ 49 | public void rejectedExecution(Runnable r, 50 | ThreadPoolExecutor executor) { 51 | taskQueue.offer(r); 52 | } 53 | }; 54 | Runnable command = new Runnable(){ 55 | public void run() { 56 | Runnable task =null; 57 | try { 58 | task = taskQueue.take();//使用具备阻塞特性的方法 59 | } catch (InterruptedException e) { 60 | return; 61 | } 62 | threadPool.execute(task); 63 | } 64 | }; 65 | ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(1); 66 | //每一次执行终止和下一次执行开始之间都存在给定的延迟 16毫秒 67 | scheduledPool.scheduleWithFixedDelay(command, 0L, 16L, TimeUnit.MILLISECONDS); 68 | threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 69 | keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue(20), 70 | new NamedThreadFactory("CoreImplServiceHandler"),myHandler){ 71 | public void afterExecute(Runnable r, Throwable t) { 72 | super.afterExecute(r, t); 73 | printException(r, t); 74 | } 75 | }; 76 | appSchedule = Executors.newScheduledThreadPool(minSchedule); 77 | } 78 | 79 | private static void printException(Runnable r, Throwable t) { 80 | if (t == null && r instanceof Future) { 81 | try { 82 | Future future = (Future) r; 83 | if (future.isDone()) 84 | future.get(); 85 | } catch (CancellationException ce) { 86 | t = ce; 87 | } catch (ExecutionException ee) { 88 | t = ee.getCause(); 89 | } catch (InterruptedException ie) { 90 | Thread.currentThread().interrupt(); 91 | } 92 | } 93 | if (t != null){ 94 | Throwable cause = t.getCause(); 95 | if(RespPackUtil.isTimeoutThrowable(cause)){ 96 | logger.error("系统自有线程池任务调用超时异常,error_msg=="+cause.getMessage()); 97 | }else{ 98 | logger.error("系统自有线程池任务异常,error_msg=="+t.getMessage(), t); 99 | } 100 | } 101 | } 102 | /** 103 | * 得到线程池的实例 104 | * @return 105 | */ 106 | public static ThreadPoolManager getInstance(){ 107 | return threadPoolManage; 108 | } 109 | 110 | public int getActiveCount(){ 111 | return threadPool.getActiveCount(); 112 | } 113 | 114 | public int getCorePoolCount(){ 115 | return corePoolSize; 116 | } 117 | /** 118 | * 任务添加到线程池中 119 | * @param paramRunnable 120 | */ 121 | public Future addExecuteTask(Runnable paramRunnable){ 122 | if(paramRunnable == null) 123 | return null; 124 | return this.threadPool.submit(paramRunnable); 125 | } 126 | 127 | public Future addExecuteTask(Callable paramRunnable){ 128 | if(paramRunnable == null) 129 | return null; 130 | return this.threadPool.submit(paramRunnable); 131 | } 132 | /** 133 | * 延时任务添加到线程池中 134 | * @param paramRunnable 135 | */ 136 | public void addDelayExecuteTask(Runnable task,int delayTime){ 137 | appSchedule.schedule(new DelayTask(task), delayTime, 138 | TimeUnit.MILLISECONDS); 139 | } 140 | 141 | /** 142 | * 延时固定周期执行 143 | * @param task 144 | * @param delay 145 | * @param period 146 | */ 147 | public void addPeriodDelayExecuteTask(Runnable task, Long delay, Long period) { 148 | this.appSchedule.scheduleWithFixedDelay(new DelayTask(task), delay, period, TimeUnit.MILLISECONDS); 149 | } 150 | 151 | public boolean isAsyncBySimple(){ 152 | return getActiveCount() <= getCorePoolCount(); 153 | } 154 | 155 | /**延时任务**/ 156 | class DelayTask implements Runnable{ 157 | 158 | private Runnable task; 159 | 160 | public DelayTask(Runnable paramTask){ 161 | this.task = paramTask; 162 | } 163 | public void run() { 164 | ThreadPoolManager.getInstance().addExecuteTask(task); 165 | } 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/Timeutils.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import java.util.Calendar; 4 | import java.util.Date; 5 | 6 | /** 7 | * Author:Caiying 8 | * Date:2016-08-14. 9 | */ 10 | public abstract class Timeutils { 11 | 12 | /** 13 | * 得到某年某月的第一天 14 | * 15 | * @param date 16 | * @return 17 | */ 18 | public static Date getFirstDayOfMonth(Date date) { 19 | Calendar c = Calendar.getInstance(); 20 | c.setTime(date); 21 | int year = c.get(Calendar.YEAR); 22 | int month = c.get(Calendar.MONTH); 23 | 24 | return getFirstDayOfMonth(year, month); 25 | } 26 | 27 | /** 28 | * 得到某年某月的第一天 29 | * 30 | * @param year 31 | * @param month 32 | * @return 33 | */ 34 | public static Date getFirstDayOfMonth(int year, int month) { 35 | Calendar cal = Calendar.getInstance(); 36 | cal.set(Calendar.YEAR, year); 37 | cal.set(Calendar.MONTH, month); 38 | cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE)); 39 | cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR)); 40 | cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE)); 41 | cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND)); 42 | cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND)); 43 | return cal.getTime(); 44 | } 45 | 46 | /** 47 | * 得到某年某月的最后一天 48 | * 49 | * @return 50 | */ 51 | public static Date getLastDayOfMonth(Date date) { 52 | Calendar c = Calendar.getInstance(); 53 | c.setTime(date); 54 | int year = c.get(Calendar.YEAR); 55 | int month = c.get(Calendar.MONTH); 56 | return getLastDayOfMonth(year, month); 57 | } 58 | 59 | /** 60 | * 得到某年某月的最后一天 61 | * 62 | * @param year 63 | * @param month 64 | * @return 65 | */ 66 | public static Date getLastDayOfMonth(int year, int month) { 67 | Calendar cal = Calendar.getInstance(); 68 | cal.set(Calendar.YEAR, year); 69 | cal.set(Calendar.MONTH, month); 70 | int value = cal.getActualMaximum(Calendar.DAY_OF_MONTH); 71 | cal.set(Calendar.DAY_OF_MONTH, value); 72 | cal.set(Calendar.HOUR, cal.getMaximum(Calendar.HOUR)); 73 | cal.set(Calendar.MINUTE, cal.getMaximum(Calendar.MINUTE)); 74 | cal.set(Calendar.SECOND, cal.getMaximum(Calendar.SECOND)); 75 | cal.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND)); 76 | return cal.getTime(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/liu/utils/XmlUtil.java: -------------------------------------------------------------------------------- 1 | package com.liu.utils; 2 | 3 | import org.apache.commons.lang.StringUtils; 4 | 5 | import com.thoughtworks.xstream.XStream; 6 | 7 | public class XmlUtil { 8 | 9 | public static Object xml2Object(String inputXml, Class[] types){ 10 | if (StringUtils.isBlank(inputXml)) { 11 | return null; 12 | } 13 | XStream xstream = new XStream(); 14 | xstream.processAnnotations(types); 15 | return xstream.fromXML(inputXml); 16 | } 17 | 18 | public static String object2Xml(Object ro, Class[] types){ 19 | if (null == ro) { 20 | return null; 21 | } 22 | XStream xstream = new XStream(); 23 | xstream.processAnnotations(types); 24 | return xstream.toXML(ro); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring/dubbo-gateway-customer.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 12 | 13 | 14 | 16 | 17 | 18 | 21 | 22 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring/dubbo-item-provider.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 11 | 12 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring/dubbo-order-provider.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 27 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring/dubbo-pk-customer.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 12 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring/dubbo-refund-provider.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring/inside-common-customer.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring/manage-common-customer.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 11 | 12 | 13 | 15 | 16 | 17 | 19 | 20 | 21 | 23 | 24 | 25 | 27 | 28 | 29 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/main/resources/config/MyBatis-Configuration.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/main/resources/config/redis_config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /src/main/resources/trade-core-spring/applicationContext-dubbo.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 12 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/main/resources/trade-core-spring/applicationContext-rpc.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/main/resources/trade-core-spring/applicationContext-trade-dao.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | 16 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/main/resources/trade-core-spring/applicationContext-trade-datasource.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 200 18 | 5 19 | 30000 20 | 20 21 | 5 22 | true 23 | 30 24 | true 25 | true 26 | false 27 | select 1 28 | 20 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 100 37 | 5 38 | 30000 39 | 20 40 | 5 41 | true 42 | 30 43 | true 44 | true 45 | false 46 | select 1 47 | 20 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/main/resources/trade-core-spring/applicationContext-trade.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 16 | 17 | 19 | 20 | 21 | classpath:db.properties 22 | classpath:trade_config.properties 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 39 | 40 | 41 | 42 | 43 | 45 | 46 | 47 | 48 | 50 | 51 | 52 | 54 | 55 | ${rocketmq.producerGroupName} 56 | 57 | 58 | 59 | 60 | 61 | 64 | 65 | ${rocketmq.consumerGroupName} 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /src/profiles/sit/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | [%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%-5level] [%logger{36}] - %msg%n 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 20 | ${catalina.base}/logs/fc_debug.log 21 | 22 | ${catalina.base}/logs/fc_debug.log.%d{yyyy-MM-dd}.%i.log 23 | 30 24 | 25 | 500MB 26 | 27 | 28 | 29 | DEBUG 30 | ACCEPT 31 | DENY 32 | 33 | 34 | [%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%-5level] [%logger{36}] - %msg%n 35 | 36 | 37 | 38 | 39 | 40 | 42 | ${catalina.base}/logs/fc_sql.log 43 | 44 | ${catalina.base}/logs/fc_sql.log.%d{yyyy-MM-dd}.%i.log 45 | 46 | 30 47 | 48 | 500MB 49 | 50 | 51 | 52 | [%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%-5level] [%logger{36}] - %msg%n 53 | 54 | 55 | 56 | 57 | 59 | ${catalina.base}/logs/fc_info.log 60 | 61 | ${catalina.base}/logs/fc_info.log.%d{yyyy-MM-dd}.%i.log 62 | 30 63 | 64 | 500MB 65 | 66 | 67 | 68 | INFO 69 | ACCEPT 70 | DENY 71 | 72 | 73 | [%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%-5level] [%logger{36}] - %msg%n 74 | 75 | 76 | 77 | 78 | 80 | ${catalina.base}/logs/fc_warn.log 81 | 82 | ${catalina.base}/logs/fc_warn.log.%d{yyyy-MM-dd}.%i.log 83 | 30 84 | 85 | 500MB 86 | 87 | 88 | 89 | WARN 90 | ACCEPT 91 | DENY 92 | 93 | 94 | [%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%-5level] [%logger{36}] - %msg%n 95 | 96 | 97 | 98 | 99 | 100 | 102 | ${catalina.base}/logs/fc_error.log 103 | 104 | ${catalina.base}/logs/fc_error.log.%d{yyyy-MM-dd}.%i.log 105 | 30 106 | 107 | 500MB 108 | 109 | 110 | 111 | ERROR 112 | ACCEPT 113 | DENY 114 | 115 | 116 | [%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%-5level] [%logger{36}] - %msg%n 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{0} - %msg%n 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | -------------------------------------------------------------------------------- /src/test/java/com/liu/sharding/service/BaseServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.liu.sharding.service; 2 | 3 | import java.io.IOException; 4 | import java.sql.SQLException; 5 | import java.util.List; 6 | 7 | import org.junit.AfterClass; 8 | import org.junit.BeforeClass; 9 | import org.junit.runner.RunWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.context.ApplicationContext; 12 | import org.springframework.context.support.ClassPathXmlApplicationContext; 13 | import org.springframework.jdbc.core.JdbcTemplate; 14 | import org.springframework.test.context.ContextConfiguration; 15 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 16 | 17 | /** 18 | * biz层测试基类 19 | * 20 | * @author liuzhihong 21 | */ 22 | @ContextConfiguration(locations = { "classpath:conf/applicationContext-sharding.xml" }) 23 | @RunWith(SpringJUnit4ClassRunner.class) 24 | public class BaseServiceTest { 25 | 26 | static { 27 | // 禁用远程调用组件 28 | } 29 | 30 | @BeforeClass 31 | public static void initTestData() throws IOException, SQLException { 32 | ApplicationContext context = new ClassPathXmlApplicationContext( 33 | "conf/applicationContext-sharding.xml"); 34 | } 35 | 36 | @AfterClass 37 | public static void afterDaoTest() { 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/com/liu/sharding/service/TestWriteShardingData.java: -------------------------------------------------------------------------------- 1 | package com.liu.sharding.service; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Date; 5 | import java.util.List; 6 | 7 | import org.junit.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | 10 | import com.liu.core.dao.TUserMapper; 11 | import com.liu.core.entity.TUser; 12 | 13 | public class TestWriteShardingData extends BaseServiceTest{ 14 | 15 | @Autowired 16 | private TUserMapper userMapper; 17 | 18 | @Test 19 | public void testInsertUser(){ 20 | List userList = new ArrayList(); 21 | TUser user1 = new TUser(); 22 | user1.setAge(21); 23 | user1.setCreateTime(new Date()); 24 | user1.setName("张三"); 25 | user1.setOuId(1401); 26 | user1.setPosition("程序猿"); 27 | userList.add(user1); 28 | 29 | TUser user2 = new TUser(); 30 | user2.setAge(25); 31 | user2.setCreateTime(new Date()); 32 | user2.setName("李四"); 33 | user2.setOuId(1401); 34 | user2.setPosition("程序猿"); 35 | userList.add(user2); 36 | 37 | TUser user3 = new TUser(); 38 | user3.setAge(22); 39 | user3.setCreateTime(new Date()); 40 | user3.setName("小珍"); 41 | user3.setOuId(1402); 42 | user3.setPosition("程序猿"); 43 | userList.add(user3); 44 | 45 | for(TUser user : userList){ 46 | userMapper.insertSelective(user); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/test/resources/conf/MyBatis-Configuration.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/test/resources/conf/applicationContext-sharding-dao.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | 16 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/test/resources/conf/applicationContext-sharding-datasource.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | true 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/test/resources/conf/applicationContext-sharding.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/test/resources/conf/db.properties: -------------------------------------------------------------------------------- 1 | database.wirte.driverClassName=com.mysql.jdbc.Driver 2 | database.wirte.url=jdbc:mysql://url(sit69):3306/sharding-jdbc?autoReconnect=true&characterEncoding=UTF8&allowMultiQueries=true 3 | database.wirte.username=root 4 | database.wirte.password=root632 -------------------------------------------------------------------------------- /src/test/resources/sqlMaps/TOuInfoMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | and ${criterion.condition} 21 | 22 | 23 | and ${criterion.condition} #{criterion.value} 24 | 25 | 26 | and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} 27 | 28 | 29 | and ${criterion.condition} 30 | 31 | #{listItem} 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | and ${criterion.condition} 50 | 51 | 52 | and ${criterion.condition} #{criterion.value} 53 | 54 | 55 | and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} 56 | 57 | 58 | and ${criterion.condition} 59 | 60 | #{listItem} 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | id, ou_id, ou_name, ou_address, cretae_time, update_time 72 | 73 | 87 | 93 | 94 | delete from t_ou_info 95 | where id = #{id,jdbcType=BIGINT} 96 | 97 | 98 | delete from t_ou_info 99 | 100 | 101 | 102 | 103 | 104 | insert into t_ou_info (id, ou_id, ou_name, 105 | ou_address, cretae_time, update_time 106 | ) 107 | values (#{id,jdbcType=BIGINT}, #{ouId,jdbcType=INTEGER}, #{ouName,jdbcType=VARCHAR}, 108 | #{ouAddress,jdbcType=VARCHAR}, #{cretaeTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP} 109 | ) 110 | 111 | 112 | insert into t_ou_info 113 | 114 | 115 | id, 116 | 117 | 118 | ou_id, 119 | 120 | 121 | ou_name, 122 | 123 | 124 | ou_address, 125 | 126 | 127 | cretae_time, 128 | 129 | 130 | update_time, 131 | 132 | 133 | 134 | 135 | #{id,jdbcType=BIGINT}, 136 | 137 | 138 | #{ouId,jdbcType=INTEGER}, 139 | 140 | 141 | #{ouName,jdbcType=VARCHAR}, 142 | 143 | 144 | #{ouAddress,jdbcType=VARCHAR}, 145 | 146 | 147 | #{cretaeTime,jdbcType=TIMESTAMP}, 148 | 149 | 150 | #{updateTime,jdbcType=TIMESTAMP}, 151 | 152 | 153 | 154 | 160 | 161 | update t_ou_info 162 | 163 | 164 | id = #{record.id,jdbcType=BIGINT}, 165 | 166 | 167 | ou_id = #{record.ouId,jdbcType=INTEGER}, 168 | 169 | 170 | ou_name = #{record.ouName,jdbcType=VARCHAR}, 171 | 172 | 173 | ou_address = #{record.ouAddress,jdbcType=VARCHAR}, 174 | 175 | 176 | cretae_time = #{record.cretaeTime,jdbcType=TIMESTAMP}, 177 | 178 | 179 | update_time = #{record.updateTime,jdbcType=TIMESTAMP}, 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | update t_ou_info 188 | set id = #{record.id,jdbcType=BIGINT}, 189 | ou_id = #{record.ouId,jdbcType=INTEGER}, 190 | ou_name = #{record.ouName,jdbcType=VARCHAR}, 191 | ou_address = #{record.ouAddress,jdbcType=VARCHAR}, 192 | cretae_time = #{record.cretaeTime,jdbcType=TIMESTAMP}, 193 | update_time = #{record.updateTime,jdbcType=TIMESTAMP} 194 | 195 | 196 | 197 | 198 | 199 | update t_ou_info 200 | 201 | 202 | ou_id = #{ouId,jdbcType=INTEGER}, 203 | 204 | 205 | ou_name = #{ouName,jdbcType=VARCHAR}, 206 | 207 | 208 | ou_address = #{ouAddress,jdbcType=VARCHAR}, 209 | 210 | 211 | cretae_time = #{cretaeTime,jdbcType=TIMESTAMP}, 212 | 213 | 214 | update_time = #{updateTime,jdbcType=TIMESTAMP}, 215 | 216 | 217 | where id = #{id,jdbcType=BIGINT} 218 | 219 | 220 | update t_ou_info 221 | set ou_id = #{ouId,jdbcType=INTEGER}, 222 | ou_name = #{ouName,jdbcType=VARCHAR}, 223 | ou_address = #{ouAddress,jdbcType=VARCHAR}, 224 | cretae_time = #{cretaeTime,jdbcType=TIMESTAMP}, 225 | update_time = #{updateTime,jdbcType=TIMESTAMP} 226 | where id = #{id,jdbcType=BIGINT} 227 | 228 | -------------------------------------------------------------------------------- /src/test/resources/sqlMaps/TUserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | and ${criterion.condition} 22 | 23 | 24 | and ${criterion.condition} #{criterion.value} 25 | 26 | 27 | and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} 28 | 29 | 30 | and ${criterion.condition} 31 | 32 | #{listItem} 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | and ${criterion.condition} 51 | 52 | 53 | and ${criterion.condition} #{criterion.value} 54 | 55 | 56 | and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} 57 | 58 | 59 | and ${criterion.condition} 60 | 61 | #{listItem} 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | id, ou_id, name, age, position, create_time, update_time 73 | 74 | 88 | 94 | 95 | delete from t_user 96 | where id = #{id,jdbcType=BIGINT} 97 | 98 | 99 | delete from t_user 100 | 101 | 102 | 103 | 104 | 105 | insert into t_user (id, ou_id, name, 106 | age, position, create_time, 107 | update_time) 108 | values (#{id,jdbcType=BIGINT}, #{ouId,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, 109 | #{age,jdbcType=INTEGER}, #{position,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, 110 | #{updateTime,jdbcType=TIMESTAMP}) 111 | 112 | 113 | insert into t_user 114 | 115 | 116 | id, 117 | 118 | 119 | ou_id, 120 | 121 | 122 | name, 123 | 124 | 125 | age, 126 | 127 | 128 | position, 129 | 130 | 131 | create_time, 132 | 133 | 134 | update_time, 135 | 136 | 137 | 138 | 139 | #{id,jdbcType=BIGINT}, 140 | 141 | 142 | #{ouId,jdbcType=INTEGER}, 143 | 144 | 145 | #{name,jdbcType=VARCHAR}, 146 | 147 | 148 | #{age,jdbcType=INTEGER}, 149 | 150 | 151 | #{position,jdbcType=VARCHAR}, 152 | 153 | 154 | #{createTime,jdbcType=TIMESTAMP}, 155 | 156 | 157 | #{updateTime,jdbcType=TIMESTAMP}, 158 | 159 | 160 | 161 | 167 | 168 | update t_user 169 | 170 | 171 | id = #{record.id,jdbcType=BIGINT}, 172 | 173 | 174 | ou_id = #{record.ouId,jdbcType=INTEGER}, 175 | 176 | 177 | name = #{record.name,jdbcType=VARCHAR}, 178 | 179 | 180 | age = #{record.age,jdbcType=INTEGER}, 181 | 182 | 183 | position = #{record.position,jdbcType=VARCHAR}, 184 | 185 | 186 | create_time = #{record.createTime,jdbcType=TIMESTAMP}, 187 | 188 | 189 | update_time = #{record.updateTime,jdbcType=TIMESTAMP}, 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | update t_user 198 | set id = #{record.id,jdbcType=BIGINT}, 199 | ou_id = #{record.ouId,jdbcType=INTEGER}, 200 | name = #{record.name,jdbcType=VARCHAR}, 201 | age = #{record.age,jdbcType=INTEGER}, 202 | position = #{record.position,jdbcType=VARCHAR}, 203 | create_time = #{record.createTime,jdbcType=TIMESTAMP}, 204 | update_time = #{record.updateTime,jdbcType=TIMESTAMP} 205 | 206 | 207 | 208 | 209 | 210 | update t_user 211 | 212 | 213 | ou_id = #{ouId,jdbcType=INTEGER}, 214 | 215 | 216 | name = #{name,jdbcType=VARCHAR}, 217 | 218 | 219 | age = #{age,jdbcType=INTEGER}, 220 | 221 | 222 | position = #{position,jdbcType=VARCHAR}, 223 | 224 | 225 | create_time = #{createTime,jdbcType=TIMESTAMP}, 226 | 227 | 228 | update_time = #{updateTime,jdbcType=TIMESTAMP}, 229 | 230 | 231 | where id = #{id,jdbcType=BIGINT} 232 | 233 | 234 | update t_user 235 | set ou_id = #{ouId,jdbcType=INTEGER}, 236 | name = #{name,jdbcType=VARCHAR}, 237 | age = #{age,jdbcType=INTEGER}, 238 | position = #{position,jdbcType=VARCHAR}, 239 | create_time = #{createTime,jdbcType=TIMESTAMP}, 240 | update_time = #{updateTime,jdbcType=TIMESTAMP} 241 | where id = #{id,jdbcType=BIGINT} 242 | 243 | --------------------------------------------------------------------------------