IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> SpringBootWebSocket断线重连亲测可用 -> 正文阅读

[Java知识库]SpringBootWebSocket断线重连亲测可用

作者:language-java
      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <!-- <version>2.3.0</version> -->
        </dependency>

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
             <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>1.3.5</version>
        </dependency>
package com.xin;
import com.xin.net.InitSystemSession;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.WebApplicationInitializer;

import javax.annotation.PostConstruct;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
@SpringBootApplication
@EnableTransactionManagement
@MapperScan("com.xin.mapper")
public class ChatApplication extends SpringBootServletInitializer implements WebApplicationInitializer
{
    @Value("${hostName}")
    private String roleName;
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(ChatApplication.class, args);
    }
    private static final WebSocketContainer CONTAINER = ContainerProvider.getWebSocketContainer();
    public static Session systemSession;
    public void onMessageToSystemService() throws DeploymentException, IOException
    {
        try {
            Session session = CONTAINER.connectToServer(InitSystemSession.class, URI.create("ws://localhost:9999/route/systemRoute/1024*1024*1024*1024"));
            systemSession=session;
            System.out.println(session.toString()+"\t连接成功");
        }catch (Exception e)
        {
            System.out.println(e.toString()+"\t路由异常");
        }
    }
}

quartz配置类

package com.xin.config;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * @description: some desc
 * @author: DXX
 * @email: xxx@xx.com
 * @date: 2022/2/23 10:16
 */
@Configuration
public class QuartzConfig
{
    @Autowired
    private JobFactory jobFactory;
    @Bean("schedulerFactoryBean")
    public SchedulerFactoryBean schedulerFactoryBean()
    {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setJobFactory(jobFactory);
        schedulerFactoryBean.setOverwriteExistingJobs(true);
        schedulerFactoryBean.setStartupDelay(1);//延时加载
        schedulerFactoryBean.setConfigLocation(new ClassPathResource("/quartz.properties"));
        return schedulerFactoryBean;
    }
    @Bean
    public Scheduler scheduler(@Qualifier("schedulerFactoryBean")SchedulerFactoryBean schedulerFactoryBean)
    {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        return scheduler;
    }

}

jobFactory配置类

package com.xin.config;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
/**
 * @description: some desc
 * @author: DXX
 * @email: xxx@xx.com
 * @date: 2022/2/23 10:29
 */
@Component
public class JobFactoryConfig extends AdaptableJobFactory {
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {

        Object jobInstance = super.createJobInstance(bundle);
        //进行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

quartz任务类

package com.xin.job;

import com.xin.ChatApplication;
import org.apache.commons.logging.Log;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @description: some desc
 * @author: DXX
 * @email: xxx@xx.com
 * @date: 2022/3/12 11:32
 */
@Component("lineLifeJobQuartz")
public class LineLifeJob extends QuartzJobBean
{
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException
    {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd:hh:mm:ss");
        String format = simpleDateFormat.format(date);
        System.out.println("连接正常\t"+format);
        if(ChatApplication.systemSession==null||ChatApplication.systemSession.isOpen()==false)
        {
            Slf4jImpl  slf4j=  new Slf4jImpl("com.xin.job.LineLifeJob");


            slf4j.debug("连接正常\t"+format);
            try {
                new ChatApplication().onMessageToSystemService();
                System.out.println("路由连接失败尝试重新连接");
            }catch (Exception e)
            {
                System.out.println(e.toString()+"\t连接服务端失败");
            }
        }
    }
}

默认任务配置类,每10秒监听一次服务器

package com.xin.config;

import com.xin.job.LineLifeJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description: some desc
 * @author: DXX
 * @email: xxx@xx.com
 * @date: 2022/2/23 11:02
 */
@Configuration
public class DefaultJobConfig {
    @Value("${clearMessageTIme}")
    private String clearMessageTime;
    @Autowired
    private Scheduler scheduler;
    @Bean("lineLifeJob")
    public Scheduler lineLifeScheduler()
    {
        try {
            JobDetail jobDetail = JobBuilder.newJob(LineLifeJob.class)
                    .withIdentity("lineLifeJob","lineLifeJobGroup")
                    .build();
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("lineLifeJobTrigger","linLifeJobTriggerGroup")
                    .withSchedule(CronScheduleBuilder.cronSchedule("*/10 * * * * ?"))
                    .build();
            scheduler.scheduleJob(jobDetail,trigger);
            return scheduler;
        }catch (Exception e){
            System.out.println(e.toString());
        }
        return scheduler;
    }
}

quartz配置文件


org.quartz.jobStore.useProperties:true
org.quartz.scheduler.instanceName:DefaultQuartzScheduler
org.quartz.scheduler.instanceId=AUTO
org.quartz.threadPool.class:org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount:1
org.quartz.threadPool.threadPriority:1
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread:true
org.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.isClustered=false
org.quartz.jobStore.clusterCheckinInterval=20000
org.quartz.jobStore.tablePrefix=qrtz_
org.quartz.jobStore.dataSource=myDS
org.quartz.dataSource.myDS.driver=com.mysql.jdbc.Driver
org.quartz.dataSource.myDS.URL=jdbc:mysql://localhost:3306/erpChat?serverTimezone=GMT&characterEncoding=utf-8
org.quartz.dataSource.myDS.user=root
org.quartz.dataSource.myDS.password=123456
org.quartz.dataSource.myDS.maxConnections=5

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-03-13 21:36:26  更:2022-03-13 21:40:42 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 9:17:19-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码