作者 shenhailong

修改payfees 类型 添加websocket 通信

... ... @@ -53,6 +53,18 @@
<version>2.8.6</version>
</dependency>
<!--websocket 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-log -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-log</artifactId>
<version>5.2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
... ...
package com.sunyo.energy.location.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunyo.energy.location.controller.response.ResultJson;
import com.sunyo.energy.location.dao.PayResponseMapper;
import com.sunyo.energy.location.model.PayResponse;
import com.sunyo.energy.location.websocket.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
... ... @@ -11,8 +14,11 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Controller
... ... @@ -62,7 +68,7 @@ public class PayRseponeController {
@RequestParam(value = "USRMSG", required = false) String USRMSG,
@RequestParam(value = "USRINFO", required = false) String USRINFO,
@RequestParam(value = "PAYTYPE", required = false) String PAYTYPE,
@RequestParam(value = "SIGN", required = false) String SIGN){
@RequestParam(value = "SIGN", required = false) String SIGN) throws IOException {
PayResponse payResponse = new PayResponse();
payResponse.setId(UUID.randomUUID().toString());
... ... @@ -87,6 +93,12 @@ public class PayRseponeController {
int i = payResponseMapperl.insertSelective(payResponse);
if (i>0){
msg=1;
WebSocketServer webSocketServer = new WebSocketServer();
JSONObject jsonObject = new JSONObject();
jsonObject.put("orderNumber", ORDERID);
jsonObject.put("success", SUCCESS);
webSocketServer.broadcast(jsonObject.toJSONString());
}
return i==1? new ResultJson("200","支付回执信息接受成功"):new ResultJson("500","支付回执信息接受失败");
}
... ...
package com.sunyo.energy.location.model;
import java.math.BigDecimal;
import java.util.Date;
public class PayRecords {
private Integer id;
private Long payfees;
private BigDecimal payfees;
private Integer payuserid;
... ... @@ -43,11 +44,11 @@ public class PayRecords {
this.id = id;
}
public Long getPayfees() {
public BigDecimal getPayfees() {
return payfees;
}
public void setPayfees(Long payfees) {
public void setPayfees(BigDecimal payfees) {
this.payfees = payfees;
}
... ...
... ... @@ -177,17 +177,20 @@ public class WaterMeterServiceImp implements WaterMeterService {
// 成功生成水费订单
PayRecords payRecords = payRecords(payFees, wmId, userId, realName);
// 请求返回二维码lujing
String s = QrDemo.orUrl(payRecords.getOrdernumber(), payFees);
String url = QrDemo.orUrl(payRecords.getOrdernumber(), payFees);
if(!"".equals(url)){
payRecords.setReamke2(url);
// 返回map 包含订单号 二维码url
Map<String, Object> map = new HashMap<>();
map.put("url",url);
map.put("orderNumber", payRecords.getOrdernumber());
resultJson.setData(map);
}
int i = payRecordsMapper.insertSelective(payRecords);
if(i>0){
resultJson.setCode("200");
}
if (!"".equals(s)){
resultJson.setData(s);
}
return resultJson;
}
... ... @@ -230,7 +233,7 @@ public class WaterMeterServiceImp implements WaterMeterService {
PayRecords payRecords = new PayRecords();
payRecords.setOrdernumber(AllUtils.getOrderIdByTime());
payRecords.setPayfees(Long.valueOf(payFees));
payRecords.setPayfees(new BigDecimal(payFees));
payRecords.setPaystatus(false);
payRecords.setPaytype(false);
payRecords.setReamke1("0");
... ...
package com.sunyo.energy.location.websocket;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
/**
* 添加fastjson的转换
*/
@Configuration
public class FastjsonConverter {
@Bean
public HttpMessageConverters customConverters() {
// 定义一个转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 添加fastjson的配置信息 比如 :是否要格式化返回的json数据
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
// 处理中文乱码问题1
// 处理中文乱码问题2
fastJsonConfig.setCharset(Charset.forName("UTF-8"));
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
//fastMediaTypes.add(MediaType.valueOf("text/plain;charset=UTF-8"));
//fastMediaTypes.add(MediaType.valueOf("text/html;charset=UTF-8"));
fastConverter.setSupportedMediaTypes(fastMediaTypes);
// 在转换器中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setDefaultCharset(Charset.forName("UTF-8"));
stringConverter.setSupportedMediaTypes(fastMediaTypes);
// 将转换器添加到converters中
return new HttpMessageConverters(stringConverter,fastConverter);
}
}
\ No newline at end of file
... ...
package com.sunyo.energy.location.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
... ...
package com.sunyo.energy.location.websocket;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
/**
* WebSocketServer
* @author zhengkai.blog.csdn.net
*/
@ServerEndpoint("/imserver")
@Component
public class WebSocketServer {
static Log log= LogFactory.get(WebSocketServer.class);
/**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
private static int onlineCount = 0;
/**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
/**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
private Session session;
/**接收userId*/
private String orderNum="";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
this.orderNum=orderNum;
if(webSocketMap.containsKey(orderNum)){
webSocketMap.remove(orderNum);
webSocketMap.put(orderNum,this);
//加入set中
}else{
webSocketMap.put(orderNum,this);
//加入set中
addOnlineCount();
//在线数加1
}
log.info("用户连接:"+orderNum+",当前在线人数为:" + getOnlineCount());
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("用户:"+orderNum+",网络异常!!!!!!");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if(webSocketMap.containsKey(orderNum)){
webSocketMap.remove(orderNum);
//从set中删除
subOnlineCount();
}
log.info("用户退出:"+orderNum+",当前在线人数为:" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
// @OnMessage
// public void onMessage(String message, Session session) {
// log.info("用户消息:"+orderNum+",报文:"+message);
// //可以群发消息
// //消息保存到数据库、redis
// if(StringUtils.isNotBlank(message)){
// try {
//// //解析发送的报文
//// JSONObject jsonObject = JSON.parseObject(message);
//// //追加发送人(防止串改)
//// jsonObject.put("fromOrderNum",this.orderNum);
//// String toUserId=jsonObject.getString("toUserId");
//// //传送给对应toUserId用户的websocket
//// if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
//// webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
//// }else{
//// log.error("请求的userId:"+toUserId+"不在该服务器上");
//// //否则不在这个服务器上,发送到mysql或者redis
//// }
// }catch (Exception e){
// e.printStackTrace();
// }
// }
// }
/**
* 群发消息
* @param content 要广播的内容
*/
public void broadcast(String content){
for (ConcurrentHashMap.Entry<String,WebSocketServer> entry : webSocketMap.entrySet()) {
WebSocketServer webSocketServerE= entry.getValue();
try {
webSocketServerE.sendMessage(content);
}catch (IOException e){
e.printStackTrace();
}
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:"+this.orderNum+",原因:"+error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 发送自定义消息
* */
public static void sendInfo(String message,@PathParam("orderNum") String orderNum) throws IOException {
log.info("发送消息到:"+orderNum+",报文:"+message);
if(StringUtils.isNotBlank(orderNum)&&webSocketMap.containsKey(orderNum)){
webSocketMap.get(orderNum).sendMessage(message);
}else{
log.error("用户"+orderNum+",不在线!");
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
\ No newline at end of file
... ...