SpringBoot(九)--- HttpClient、Spring Cache、Spring Task、WebSocket

发布于:2025-06-26 ⋅ 阅读:(20) ⋅ 点赞:(0)

 

目录

一、HttpClient入门

二、Spring Cache

​编辑

1. Spring Cahce常用注解

2. Spring Cache入门案例

三、Spring Task

1. cron表达式

2. 入门案例

四、WebSocket


前言

HttpClient是Apache Jakarta Common下的子项目,可以用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。

在pom文件中导入HttpClient的Maven坐标:

一、HttpClient入门

通过单元测试来测试HttpClient发送GET和POST请求。

发送GET请求:

  /**
     * 测试通过HttpClient发送GET方式请求
     */
    @Test
    public void getTest() throws IOException {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建Http请求对象
        HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");

        // 调用HttpClient的execute方法发送请求
        CloseableHttpResponse response = httpClient.execute(httpGet);

        // 获取服务端返回的状态码
        int code = response.getStatusLine().getStatusCode();
        System.out.println("响应的状态码为:" + code);

        // 获取返回的数据
        HttpEntity entity = response.getEntity();
        String body = EntityUtils.toString(entity);
        System.out.println("服务端返回的数据为:" + body);

        response.close();
        httpClient.close();
    }

发送POST请求,因为POST请求还需要传递参数,代码中多出了传递参数的部分:

    /**
     * 测试通过HttpClient发送POST请求
     */
    @Test
    public void testPost() throws JSONException, IOException {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();



        // 创建Http请求对象
        HttpPost httpPost = new HttpPost("Http://localhost:8080/admin/employee/login");
        // 因为Post请求需要传递参数,上面的请求路径需要传递一个JSON格式的参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "admin");
        jsonObject.put("password", "123456");

        // 这句代码是用于指定参数
        StringEntity entity = new StringEntity(jsonObject.toString());
        // 指定请求编码方式
        entity.setContentEncoding("utf-8");
        // 指定数据格式
        entity.setContentType("application/json");

        httpPost.setEntity(entity);



        // 调用HttpClient的execute方法发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 解析数据
        int code = response.getStatusLine().getStatusCode();
        System.out.println("响应码为:" + code);
        HttpEntity entity1 = response.getEntity();
        String string = EntityUtils.toString(entity1);
        System.out.println("响应回来的数据为:" + string);

        response.close();
        httpClient.close();
    }

二、Spring Cache

1. Spring Cahce常用注解

2. Spring Cache入门案例

先在启动类上加上@EnableCaching注解

@CachePut注解:

cacheNames指定存入Redis的缓存的名称,因为每一个用户信息都不同,然后通过指定每一个特殊的key来生成最终的key值(cacaeNames + key)。

@Cacheable注解:

利用注解在Redis中查询数据时,要注意指定的cachaNames要和存入Redis的cacheNames的名字要一致。例如,存入时是userCache,查询时就需要是userCache。

@CacheEvict注解:

三、Spring Task

Spring Task可以按照约定的时间自动执行某个代码逻辑。

1. cron表达式

cron表达式其实就是一个字符串,通过cron表达式可以定义任务触发的时间。

构成规则:分为6或7个域,由空格分隔开,每个域代表一个含义。每个域的含义分别为:秒、分钟、小时、日、月、周、年(年可选)。

注意:日和周是冲突的,周代表的是星期几,有日的话周就填成?,有周的话日就填成?。

2. 入门案例

四、WebSocket

WebSocket是基于TCP的一种新的网路协议。它实现了浏览器和服务器全双工通信-----浏览器和服务器只需要完成一次握手,两者之间就可以创建持久型的连接,并进行双向数据传输。(即浏览器和服务器都可以主动向对方传输数据)。

从下图可以看到HTTP协议和WebSocket协议的区别,HTTP是一种“请求-响应模式”,只有客户端向服务器端发送请求之后,服务器端才会向客户端发送数据。而WebSocket只有客户端与服务器端建立了连接,服务器端就可以直接向客户点发送数据,不需要客户端进行请求(就像两个人打电话那样)。

入门案例:

WebSocketServer代码,{sid}是前端传过来的一个随机数,代码基本上是固定的:

/**
 * WebSocket服务
 */
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {

    //存放会话对象
    private static Map<String, Session> sessionMap = new HashMap();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端:" + sid + "建立连接");
        sessionMap.put(sid, session);
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        System.out.println("收到来自客户端:" + sid + "的信息:" + message);
    }

    /**
     * 连接关闭调用的方法

     */
    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("连接断开:" + sid);
        sessionMap.remove(sid);
    }

    /**
     * 群发
     */
    public void sendToAllClient(String message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                //服务器向客户端发送消息
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

WebSocketConfiguration代码如下:

/**
 * WebSocket配置类,用于注册WebSocket的Bean
 */
@Configuration
public class WebSocketConfiguration {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

一般服务器端向客户端传递的是JSON格式的数据。

    // 客户端用户进行催单
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.selectOrderById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        String number = orders.getNumber();   // 订单号
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号" + number);

        String json = JSON.toJSONString(map);
        // WebSocket向客户端推送消息
        webSocketServer.sendToAllClient(json);
    }


网站公告

今日签到

点亮在社区的每一天
去签到