常见的框架

JSP

权限认证框架

sa-token

springboot-security

okhttp

okhttp可以在项目中发起http请求 

和http的区别及应用场景

发起http请求的场景

EasyExcel

快速处理excel的框架




EasyExcel.read()读到的数据是通过ExcelDataListener ()处理的




    // 模拟数据
    private List<UserData> dataList = new ArrayList<>();

    // 接收前端上传的 Excel 文件
    @PostMapping("/upload")
    public String uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
        // 使用 EasyExcel 读取上传的 Excel 文件数据
        EasyExcel.read(file.getInputStream(), UserData.class, new ExcelDataListener()).sheet().doRead();
        return "Upload successful!";
    }

    // 处理下载请求,将 Excel 文件返回给前端进行下载
    @GetMapping("/download")
    public void downloadExcel(HttpServletResponse response) throws IOException {
        // 准备数据
        dataList.add(new UserData("张三", 255550));
        dataList.add(new UserData("李四", 25));
        dataList.add(new UserData("王五", 30));

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=example.xlsx");

        // 使用 EasyExcel 写入 Excel 文件并返回给前端
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), UserData.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").build();
        excelWriter.write(dataList, writeSheet);
        excelWriter.finish();
    }

    // 数据监听器类,用于处理 Excel 文件中的数据
    public static class ExcelDataListener extends AnalysisEventListener<UserData> {

        @Override
        public void invoke(UserData data, AnalysisContext context) {
            // 这里可以处理从 Excel 中读取到的每一行数据,可以存入数据库或进行其他业务逻辑处理
            System.out.println("读取到数据:" + data);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            // 数据读取完成后执行的操作,如关闭资源等
        }
    }

Poi

用了处理Microsoft Office格式的文件 easyexcel是专门用了处理excel的 而这个可以处理多种

Hutool

提供了丰富的工具方法,涵盖了字符串、集合、日期、加密、文件、HTTP等多个常用功能。


    @GetMapping("/hutooltest")
    public void hutooltest() {
        // 使用字符串工具类
        String str = "Hello, Hutool!";
        String result = StrUtil.upperFirst(str);
        System.out.println(result); // 输出:Hello, Hutool!

        // 使用日期工具类
        String dateStr = "2024-07-16 12:00:00";
        Date date = DateUtil.parse(dateStr);
        System.out.println(DateUtil.formatDateTime(date)); // 输出:2024-07-16 12:00:00


        // 使用字符串工具类
        String str1 = "hello, hutool!";

        // 首字母大写
        String capitalized = StrUtil.upperFirst(str1);
        System.out.println("首字母大写:" + capitalized); // 输出:Hello, hutool!

        // 判断是否为空白字符(包括null)
        boolean isEmptyOrBlank = StrUtil.isBlank(str1);
        System.out.println("是否为空白字符:" + isEmptyOrBlank); // 输出:false

        // 字符串格式化
        String template = "This is {} example {}.";
        String result2 = StrUtil.format(template, "Hutool", "using");
        System.out.println("格式化后的字符串:" + result2); // 输出:This is Hutool example using.


        // 使用日期工具类
        String dateStr1 = "2024-07-16 12:00:00";

        // 字符串转换为日期对象
        Date date1 = DateUtil.parse(dateStr1);
        System.out.println("日期对象:" + date1); // 输出:Mon Jul 16 12:00:00 CST 2024

        // 格式化日期对象为字符串
        String formattedDate = DateUtil.formatDateTime(date1);
        System.out.println("格式化后的日期字符串:" + formattedDate); // 输出:2024-07-16 12:00:00

        // 使用文件工具类
        String filePath = "path/to/your/file.txt";

        // 判断文件是否存在
        boolean exists = FileUtil.exist(filePath);
        System.out.println("文件是否存在:" + exists); // 输出:true 或者 false

        // 创建文件
        File file = FileUtil.touch(filePath);
        System.out.println("文件创建成功:" + file.getAbsolutePath());

        // 复制文件
        String targetFilePath = "path/to/your/target/file.txt";
        File targetFile = FileUtil.copy(file, new File(targetFilePath), true);
        System.out.println("文件复制成功:" + targetFile.getAbsolutePath());



    }

Websocket

Websocket分为两类 一类是基于spring框架  一类是基于java

package com.websocket.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

//这是基于java实现websocket
//这是基于java实现websocket
//这是基于java实现websocket
//这是基于java实现websocket
//这是基于java实现websocket
//
//
//因为WebSocket是类似客户端服务端的形式(采用ws协议),那么这里的WebSocketServer其实就相当于一个ws协议的Controller
//        直接@ServerEndpoint("/imserver/{userId}") 、@Component启用即可,然后在里面实现@OnOpen开启连接,@onClose关闭连接,@onMessage接收消息等方法。
//        新建一个ConcurrentHashMap用于接收当前userId的WebSocket或者Session信息,方便IM之间对userId进行推送消息。单机版实现到这里就可以。
//        集群版(多个ws节点)还需要借助 MySQL或者 Redis等进行订阅广播方式处理,改造对应的 sendMessage方法即可。


/**
 * WebSocket的操作类
 */
@Component
@Slf4j
/**
 * html页面与之关联的接口
 * var reqUrl = "http://localhost:8081/websocket/" + cid;
 * socket = new WebSocket(reqUrl.replace("http", "ws"));
 */
@ServerEndpoint("/websocket/{sid}")
public class WebSocketServer {

    /**
     * 静态变量,用来记录当前在线连接数,线程安全的类。
     */
    private static AtomicInteger onlineSessionClientCount = new AtomicInteger(0);

    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> onlineSessionClientMap = new ConcurrentHashMap<>();

    /**
     * 连接sid和连接会话
     */
    private String sid;
    private Session session;

    /**
     * 连接建立成功调用的方法。由前端<code>new WebSocket</code>触发
     *
     * @param sid     每次页面建立连接时传入到服务端的id,比如用户id等。可以自定义。
     * @param session 与某个客户端的连接会话,需要通过它来给客户端发送消息
     */
    @OnOpen
    public void onOpen(@PathParam("sid") String sid, Session session) {
        /**
         * session.getId():当前session会话会自动生成一个id,从0开始累加的。
         */
        log.info("连接建立中 ==> session_id = {}, sid = {}", session.getId(), sid);
        //加入 Map中。将页面的sid和session绑定或者session.getId()与session
        //onlineSessionIdClientMap.put(session.getId(), session);
        onlineSessionClientMap.put(sid, session);

        //在线数加1
        onlineSessionClientCount.incrementAndGet();
        this.sid = sid;
        this.session = session;
        sendToOne(sid, "连接成功");
        log.info("连接建立成功,当前在线数为:{} ==> 开始监听新连接:session_id = {}, sid = {},。", onlineSessionClientCount, session.getId(), sid);
    }

    /**
     * 连接关闭调用的方法。由前端<code>socket.close()</code>触发
     *
     * @param sid
     * @param session
     */
    @OnClose
    public void onClose(@PathParam("sid") String sid, Session session) {
        //onlineSessionIdClientMap.remove(session.getId());
        // 从 Map中移除
        onlineSessionClientMap.remove(sid);

        //在线数减1
        onlineSessionClientCount.decrementAndGet();
        log.info("连接关闭成功,当前在线数为:{} ==> 关闭该连接信息:session_id = {}, sid = {},。", onlineSessionClientCount, session.getId(), sid);
    }

    /**
     * 收到客户端消息后调用的方法。由前端<code>socket.send</code>触发
     * * 当服务端执行toSession.getAsyncRemote().sendText(xxx)后,前端的socket.onmessage得到监听。
     *
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        /**
         * html界面传递来得数据格式,可以自定义.
         * {"sid":"user-1","message":"hello websocket"}
         */
        JSONObject jsonObject = JSON.parseObject(message);
        String toSid = jsonObject.getString("sid");
        String msg = jsonObject.getString("message");
        log.info("服务端收到客户端消息 ==> fromSid = {}, toSid = {}, message = {}", sid, toSid, message);

        /**
         * 模拟约定:如果未指定sid信息,则群发,否则就单独发送
         */
        if (toSid == null || toSid == "" || "".equalsIgnoreCase(toSid)) {
            sendToAll(msg);
        } else {
            sendToOne(toSid, msg);
        }
    }

    /**
     * 发生错误调用的方法
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket发生错误,错误信息为:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 群发消息
     *
     * @param message 消息
     */
    private void sendToAll(String message) {
        // 遍历在线map集合
        onlineSessionClientMap.forEach((onlineSid, toSession) -> {
            // 排除掉自己
            if (!sid.equalsIgnoreCase(onlineSid)) {
                log.info("服务端给客户端群发消息 ==> sid = {}, toSid = {}, message = {}", sid, onlineSid, message);
                toSession.getAsyncRemote().sendText(message);
            }
        });
    }

    /**
     * 指定发送消息
     *
     * @param toSid
     * @param message
     */
    private void sendToOne(String toSid, String message) {
        // 通过sid查询map中是否存在
        Session toSession = onlineSessionClientMap.get(toSid);
        if (toSession == null) {
            log.error("服务端给客户端发送消息 ==> toSid = {} 不存在, message = {}", toSid, message);
            return;
        }
        // 异步发送
        log.info("服务端给客户端发送消息 ==> toSid = {}, message = {}", toSid, message);
        toSession.getAsyncRemote().sendText(message);
        /*
        // 同步发送
        try {
            toSession.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("发送消息失败,WebSocket IO异常");
            e.printStackTrace();
        }*/
    }

}

Netty

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值