使用redission实现定时器+操作缓存(桶概念、分布式锁)

目录

1.加入maven依赖

2.编写application.yaml

3.编写RedissonConfig,配置RedissonClient的信息

4.编写定时器TimerService接口

5.编写定时器TimerService的实现子类,实现定时器

6.启动类加上@EnableScheduling注解并启动项目

7.编写缓存LocalCacheUtils,实现缓存


1.加入maven依赖

<!-- https://mvnrepository.com/artifact/org.redisson/redisson -->
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.17.0</version>
</dependency>

2.编写application.yaml

spring:
  redis:
    host: localhost
    port: 6379
    password: 111
    database: 0
timer:
  auto-check: "0 0/1 * * * ?"

spring.redis.* : 配置redis

timer.auto-check : 使用cron表达式,设置定时器多久执行一次,key值可自定义

cron表达式生成网址 : 在线Cron表达式生成器


3.编写RedissonConfig,配置RedissonClient的信息

import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.redisson.api.RedissonClient;
 
/**
 * @author 59899
 */
@Configuration
public class RedissonConfig {
 
    @Value("${spring.redis.host}")
    private String host;
 
    @Value("${spring.redis.port}")
    private String port;
 
    @Value("${spring.redis.password}")
    private String password;
 
    @Value("${spring.redis.database}")
    private int database;
    
    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://" + host + ":" + port)
                .setPassword(password).setDatabase(database);
        config.useSingleServer().setConnectionMinimumIdleSize(5);
        return Redisson.create(config);
    }
}

读取编写好的application.yaml文件,

并取得redis的配置信息,添加到Config中


4.编写定时器TimerService接口

/**
 * @author 59899
 */
public interface TimerService {

    /**
     * 定时器
     */
    void timer();

}

5.编写定时器TimerService的实现子类,实现定时器


import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 59899
 */
@Slf4j
@Service
public class TimerServiceImpl implements TimerService {

    @Autowired
    RedissonClient redissonClient;

    private final String schedule_lock = "timer:auto_check_lock";

    @Scheduled(cron = "${timer.auto-check: 0 0/1 * * * ?}")
    @Override
    public void timer() {
        log.info("trigger scheduled auto check");
        RLock lock = redissonClient.getLock(schedule_lock);
        try {
            //设置最长锁占用时间,避免服务挂掉导致锁无法释放
            if (lock.tryLock(0, 10, TimeUnit.MINUTES)) {
                // 写入需要定时执行的代码
                System.out.println(new Date()+": 定时器执行任务");
            } else {
                log.info("checkAndAutoReplay ignore,maybe another instance is running!");
            }
        } catch (InterruptedException e) {
            log.error("triggerRawReplyJob exception!", e);
        } finally {
            lock.unlock();
        }
    }
}

使用配置好的RedissonClient,并获取锁,

使用@Scheduled()并读取application.yaml中自定义的cron表达式设置定时器多久执行一次


6.启动类加上@EnableScheduling注解并启动项目

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * @author 59899
 */
@SpringBootApplication
@EnableScheduling
public class RedissonApplication {
    public static void main(String[] args) {
        SpringApplication.run(RedissonApplication.class, args);
    }
}

 定时器启动成功


7.编写缓存LocalCacheUtils,实现缓存

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 59899
 */
@Slf4j
@Component
public class LocalCacheUtils {

    @Autowired
    RedissonClient redissonClient;

    /**
     * 添加缓存
     * @param key key
     * @param value value
     */
    public void add(String key, String value) {
        //根据key获取bucket桶对象
        RBucket<Object> bucket = redissonClient.getBucket(key);
        //判读是否存在,并打印日志信息
        if (!bucket.isExists()) {
            log.info("add data");
        }else {
            log.info("update data");
        }
        //添加缓存,若已存在,则替换,设置缓存超时时间
        bucket.set(value, 60, TimeUnit.SECONDS);
    }


    /**
     * 在缓存中获取信息
     * @param key key
     * @return 信息结果
     */
    public Object get(String key) {
        //根据key获取bucket桶对象
        RBucket<Object> bucket = redissonClient.getBucket(key);
        //判读是否存在,并打印日志信息
        if (!bucket.isExists()) {
            log.info("error");
        }
        log.info("cache is {}", bucket.get());
        return bucket.get();
    }

    /**
     * 删除缓存信息
     * @param key key
     */
    public void delete(String key) {
        //根据key获取bucket桶对象
        RBucket<Object> bucket = redissonClient.getBucket(key);
        //判读是否存在,并打印日志信息
        if (!bucket.isExists()) {
            log.info("error");
        }
        bucket.delete();
    }
    
}

使用Bucket桶概念操作redis缓存


本篇文章分享到这里就结束啦!

点个赞再走吧~

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
中断的概念和作用: 中断是一种机制,用于在微处理器执行程序的过程中,暂停当前正在执行的任务,转而执行一个特定的代码块,然后再返回到原来的任务。中断可以用于响应外部事件(如按键、传感器信号等)或内部事件(如定时器溢出、串口接收等),实现实时响应和异步处理。 中断的作用: 1. 实时响应:中断可以立即响应外部或内部事件,使得系统能够及时处理紧急或重要的任务。 2. 异步处理:中断允许系统在执行主任务的同时,处理其他事件,提高系统的效率和灵活性。 3. 时间控制:通过定时器中断,可以实现精确的时间控制,例如定时触发任务、生成精确的时间延迟等。 4. 多任务管理:中断允许系统在多个任务之间进行切换,实现多任务管理和调度。 使用定时器进行延时操作定时器可以用来生成精确的时间延迟,以下是使用定时器进行延时操作的一般步骤: 1. 配置定时器使用STM32CubeMX或编写代码配置定时器的计数模式、预分频系数和重载值等参数。 2. 启动定时器使用HAL库提供的函数启动定时器,开始计数。 3. 等待定时器溢出:使用HAL库提供的函数或轮询定时器状态的方式,等待定时器溢出。 4. 定时器中断处理函数:在定时器溢出时,中断服务程序(ISR)会被执行,可以在ISR中进行延时结束后的处理。 以下是一个基于定时器的延时操作的示例代码: ```c #include "stm32f4xx_hal.h" TIM_HandleTypeDef htim2; void SysTick_Handler(void) { HAL_IncTick(); } void TIM2_IRQHandler(void) { HAL_TIM_IRQHandler(&htim2); } void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { if (htim->Instance == TIM2) { // 定时器溢出后的处理 } } void delay_ms(uint32_t ms) { HAL_Delay(ms); } int main(void) { HAL_Init(); SystemClock_Config(); // 初始化定时器 __HAL_RCC_TIM2_CLK_ENABLE(); htim2.Instance = TIM2; htim2.Init.Prescaler = 1000 - 1; // 设置预分频系数 htim2.Init.CounterMode = TIM_COUNTERMODE_UP; htim2.Init.Period = 10000 - 1; // 设置重载值 HAL_TIM_Base_Init(&htim2); // 启动定时器 HAL_TIM_Base_Start_IT(&htim2); while (1) { // 延时1秒 delay_ms(1000); // 延时结束后的处理 } } ``` 以上代码使用定时器TIM2生成1秒的延时,定时器溢出后会调用`HAL_TIM_PeriodElapsedCallback()`函数进行延时结束后的处理。在主循环中,使用`delay_ms()`函数实现1秒的延时。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值