jsonUtil
public class JsonUtil
{
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串。
* <p>Title: pojoToJson</p>
* <p>Description: </p>
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将json结果集转化为对象
*
* @param jsonData json数据
* @param clazz 对象中的object类型
* @return
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成pojo对象list
* <p>Title: jsonToList</p>
* <p>Description: </p>
* @param jsonData
* @param beanType
* @return
*/
public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
利用redis自增
@Service
public class SerialNumGeneration
{
@Autowired
protected DefaultRedisClient redisClient;
//生成订单号
public String createOrderNumber(String orderCode) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String todayTime = sdf.format(date);
String key = orderCode + todayTime.substring(4);
if (redisClient.get(key) == null) {
redisClient.setEx(key, String.format("%04d", 1), 24 * 60 * 60);
return key + String.format("%04d", 1);
}
Object num = redisClient.get(key);
int value = Integer.valueOf(num.toString()) + 1;
if (value == 10000) {
value = 1;
}
redisClient.set(key, String.format("%04d", value));
return key + String.format("%04d", value);
}
}
时间多加一天
//endTime 多加一天
if(storeOutBillReturnDTO.getEndTime() !=null){
Calendar c = Calendar.getInstance();
c.setTime(storeOutBillReturnDTO.getEndTime());
c.add(Calendar.DAY_OF_MONTH, 1);
storeOutBillReturnDTO.setEndTime(c.getTime());
}
rabbitMq一些配置
public class AmqpProviderConfig {
// 交换机名称
public static final String EXCHANGE = "mj-invengo-factory-exchange";
// 路由关键字
public static final String ROUTINGKEY = "mj-invengo-factory-routingKey";
private static RabbitTemplate rabbitTemplate = null;;
/**
* 连接工厂
*
* @return
*/
public static ConnectionFactory connectionFactory() {
CachingConnectionFactory factory = new CachingConnectionFactory();
String address = ReadProperties.get("RABBITMQ_ADDRESS");
factory.setAddresses(address);
factory.setUsername("root");
factory.setPassword("root");
factory.setVirtualHost("/");
factory.setPublisherConfirms(true);
return factory;
}
/**
* 获取template模板
*
* @return
*/
public static RabbitTemplate providerRabbitTemplate() {
if (rabbitTemplate == null) {
rabbitTemplate = new RabbitTemplate(connectionFactory());
rabbitTemplate.setExchange(EXCHANGE);
return rabbitTemplate;
}
return rabbitTemplate;
}
}
@Configuration
public class AmqpConsumerConfig {
@Autowired
private MqMessageListener mqMessageListener;
@Autowired
private InnerMqMessageListener innerMqMessageListener;
// 交换机名称
public static final String EXCHANGE = "mj-lead-factory-exchange";
// 路由关键字
public static final String ROUTINGKEY = "mj-lead-factory-routingKey";
// 门店工厂交换机名称
public static final String INNEREXCHANGE = "mj-invengo-sf-exchange";
//门店工厂路由关键字
public static final String INNERROUTINGKEY = "mj-invengo-sf-routingKey";
@Bean
public DirectExchange defaultExchange() {
return new DirectExchange(EXCHANGE);
}
@Bean
public Queue queue() {
return new Queue("mj-lead-factory-queue", true);
}
@Bean
public Binding binding() {
return BindingBuilder.bind(queue()).to(defaultExchange()).with(ROUTINGKEY);
}
/**
* 消息监听
*
* @return
*/
@Bean
public SimpleMessageListenerContainer messageContainer() {
if( ReadProperties.get("OUTER_LISTENER").equals("false"))
return null;
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(mqConnectionFactory());
container.setQueues(queue());
container.setExposeListenerChannel(true);
container.setMaxConcurrentConsumers(1);
container.setConcurrentConsumers(1);
container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
// 设计消息监听
container.setMessageListener(this.mqMessageListener);
return container;
}
/**
* 连接工厂
*
* @return
*/
@Bean
public ConnectionFactory mqConnectionFactory() {
CachingConnectionFactory factory = new CachingConnectionFactory();
String address = ReadProperties.get("RABBITMQ_ADDRESS");
factory.setAddresses(address);
factory.setUsername("invengo");
factory.setPassword("invengMQrfid.");
factory.setVirtualHost("/");
factory.setPublisherConfirms(true);
return factory;
}
/*
* *门店工厂监听器
*/
@Bean
public SimpleMessageListenerContainer InnerMessageContainer() {
if( ReadProperties.get("INNER_LISTENER").equals("false"))
return null;
SimpleMessageListenerContainer container = new
SimpleMessageListenerContainer(mqConnectionFactory());
container.setQueues(innerQueue());
container.setExposeListenerChannel(true);
container.setMaxConcurrentConsumers(1);
container.setConcurrentConsumers(1);
container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
// 设计消息监听
container.setMessageListener(this.innerMqMessageListener);
return container;
}
@Bean
public DirectExchange innerExchange() {
return new DirectExchange(INNEREXCHANGE);
}
@Bean
public Queue innerQueue() {
return new Queue("mj-invengo-sf-queue", true);
}
@Bean
public Binding innnerBinding() {
return BindingBuilder.bind(innerQueue()).to(innerExchange()).with(INNERROUTINGKEY);
}
}
@Component
public class MqMessageListener implements ChannelAwareMessageListener {
private static final Logger logger = LoggerFactory.getLogger(MqMessageListener.class);
@Autowired
private CheckFactoryOrderExService checkFactoryOrderExService;
@Override
public void onMessage(Message message, Channel channel) throws Exception {
// TODO Auto-generated method stub
byte[] body = message.getBody();
try
{
JSONObject messageObject = JSONObject.parseObject(new String(body));
String type = messageObject.getString("type");
String data = messageObject.getString("data");
logger.warn("**********来源信息**********:" + messageObject.toJSONString());
if (!StringUtils.isEmpty(type) && BillType.SCType.containsKey(type) && !StringUtils.isEmpty(data)) {
if (Objects.equals("9", type)) {
OrderInfoDTOSC orderInfoDTOSC = JSON.parseObject(messageObject.toJSONString(),
OrderInfoDTOSC.class);
logger.info("***************调条SC接口发过来的信息为:**********"+JsonUtilsLJ.objectToJson(orderInfoDTOSC));
OrderInfoDTOSCDetial orderInfoDTOSCDetial = orderInfoDTOSC.getData();
checkFactoryOrderExService.saveOrderInfoFromSC(orderInfoDTOSCDetial);
}
// 确认消息成功消费
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
System.err.println("message data:" + new String(body));
}else{
// 不需要重试的消息
logger.error("Mq message ERROR DATA > " + messageObject);
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
}
}
catch (Exception e)
{
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
logger.error("Mq message Listener error > ", e);
}
}
}
/**
* 发送mq类
*
* @author
*
*/
@Component
public class RabbitMqSend implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
private static final Logger log = LoggerFactory.getLogger(RabbitMqSend.class);
/**
* 发送方法
*
* @param msg
* @throws Exception
*/
public void sendMsg(String msg) throws Exception {
log.warn("***********消息中间件发送的消息*************:" + msg);
CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
AmqpProviderConfig.providerRabbitTemplate().setConfirmCallback(this);
AmqpProviderConfig.providerRabbitTemplate().setReturnCallback(this);
AmqpProviderConfig.providerRabbitTemplate().convertAndSend(AmqpProviderConfig.EXCHANGE,
AmqpProviderConfig.ROUTINGKEY, msg, correlationData);
}
/**
* 将消息发送到mq server
*/
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
// TODO Auto-generated method stub
log.debug("send id:" + correlationData.getId());
if (ack) {// 调用成功
log.warn(correlationData.getId() + ":" + "发送成功.");
} else {
log.warn(correlationData.getId() + ":" + "发送失败.");
}
}
@Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
// TODO Auto-generated method stub
log.info("{message:" + message + ",replyCode:" + replyCode + ",replyText:" + replyText + ",exchange" + exchange
+ ",routingKey" + routingKey + "}");
}
public static void main(String[] args) throws Exception {
RabbitMqSend send = new RabbitMqSend();
send.sendMsg("123");
TimeUnit.SECONDS.sleep(3);
}
}