业务场景:最近做了一个小的实用项目,在内网访问情况下,决定实用Tomcat作为服务器,前后端代码都部署到上面。业务比较简单,签约的签名产生的图片实时保存到本地并且返回到页面显示
实时保存的实现 使用websocket

一、Tomcat上传图片、文件等到项目目录外的其他存储位置 Javaweb项目通过虚拟路径读取本地图片

使用 Tomcat 作为服务器的时候,如果将上传文件保存在项目路径下,每次重启服务或者打成 war 包的时候很容易丢失上传的文件,另外就是文件多了,Tomcat容易崩,于是我们配置 Tomcat 把文件保存到项目外的其他磁盘路径:
配置文件位置:Tomcat路径下,apache-tomcat-8.5.6\conf server.xml

配置内: 
 <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
 //在这里配置文件保存路径
<Context  docBase="C:/upload/images"  path="/images" />

二、文件上传 并且实时返回功能代码

2.1 上传业务接口(测试后上传到本地TomCat指定路径没有问题)

但是值得一说的是当在我们把图片上传到Linux服务器的指定位置上时却没有响应,后面会单出一文解决方案。

  @Autowired
    private WebSocketController webSocketController;
    /**
     * 上传图片
     *
     * @return
     */
    @RequestMapping(value = "/file/uploadPhotoAndCompanyName")
    ResultMsg<Object> uploadPhotoAndCompanyName(String base64,String name) {
        ResultMsg<Object> resultMsg = new ResultMsg<>();

        File file = null;
        //创建文件目录  tomcat 根目录的 server.xml
//    目录:    apache-tomcat-8.5.6\conf server.xml
//    配置:  <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
//    <Context  docBase="C:/upload/images"  path="/images" />
        String filePath = "C:/upload/images/";
//        String filePath = savePath;
        File dir = new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        String photoFileName = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64.replace("\r\n",""));
            //拼接新文件名(时间戳+5位数随机数)
            photoFileName=System.currentTimeMillis() + RandomUtil.getAllNum(5) + ".png";
            file=new File(filePath + photoFileName);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            HashMap hashMap = new HashMap();
            hashMap.put("url","/images/" + photoFileName);
            hashMap.put("name",name);
            webSocketController.groupSending(JsonUtil.toJson(hashMap));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        resultMsg.setData("/images/" + photoFileName);
        return resultMsg;
    }

2.2 WebSocketConfig

@Component
public class WebSocketConfig {
    private static BaseLog log = BaseLog.getInstance(WebSocketConfig.class.getName());
    /**
     * ServerEndpointExporter作用
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Bean
    public WebSocketClient webSocketClient() {
        try {
            WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:8080/websocket/name1"), new Draft_6455()) {

                @Override
                public void onOpen(org.java_websocket.handshake.ServerHandshake serverHandshake) {
                    log.info("[websocket] 连接成功");
                }

                @Override
                public void onMessage(String message) {
                    log.info("[websocket] 收到消息={}" + message);
                }
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.info("[websocket] 退出连接");
                }
                @Override
                public void onError(Exception ex) {
                    log.info("[websocket] 连接错误={}" + ex.getMessage());
                }
            };
            webSocketClient.connect();
            return webSocketClient;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }


}

2.3 WebSocketController

@Component
@ServerEndpoint("/websocket/{name}")
public class WebSocketController {

    private static BaseLog log = BaseLog.getInstance(WebSocketController.class.getName());
    /**
     * 与某个客户端的连接对话,需要通过它来给客户端发送消息
     */
    private Session session;
    /**
     * 标识当前连接客户端的用户名
     */
    private String name;

    private static ConcurrentHashMap<String, WebSocketController> websocketSet = new ConcurrentHashMap<>();

    @OnOpen
    public void OnOpen(Session session, @PathParam(value = "name") String name) {
        this.session = session;
        this.name = name;
        //name是用来表示唯一客户端,如果需要指定发送,需要指定发送通过name来区分
        websocketSet.put(name, this);
        log.info("[WebSocket]连接成功,当前连接人数为={} :" + websocketSet.size());
        OnMessage(name);
    }

    @OnClose
    public void OnClose() {
        websocketSet.remove(this.name);
        log.info("[WebSocket]退出成功,当前连接人数为={} : " + websocketSet.size());
    }

    @OnMessage
    public void OnMessage(String message) {
        log.info("[WebSocket]收到消息={} : " + message);
        groupSending( message);
    }

    public void groupSending(String message) {
        log.info("message : "+message);
        if (0 != websocketSet.size()) {
            for (String name : websocketSet.keySet()) {
                try {
                    websocketSet.get(name).session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public void groupSending1(String message) {
        try {
            ConcurrentHashMap.KeySetView<String, WebSocketController> strings = websocketSet.keySet();
            String s = new String();
            for (String string : strings) {
                s = string;
            }
            websocketSet.get(s).session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

三、相关推荐

WebSocket


怎么办,不写点感觉身上有蚂蚁在爬!