SpringBoot + Redis 实现键空间通知(keyspace notification)

前言

SpringBoot + Redis 可以用 Redis 的键空间通知机制实现类似延迟消息队列的功能 ,Redis2.8 后可以通过键空间通知接收那些以某种方式改变了Redis数据空间的事件通知,关于 Redis 键空间通知的配置 Redis-x64-3.2 键空间通知(keyspace notification) 之前有介绍,这里只是介绍 SpringBoot 中的同理实现。


环境

SpringBoot2.5.3 + Redis-x64-3.2.1


具体实现

  • 启动 redis,配置文件 redis.windows.conf 中设置键空间通知事件为Ex
notify-keyspace-events Ex

在这里插入图片描述

  • application.yml
redis:
    localhost: localhost
    port: 6379 
    database: 7
    password:
    # 过期事件订阅,接收7号数据库中所有key的过期事件
    listen-pattern: __keyevent@7__:expired
  • Redis 事件广播配置类
import com.coisini.springbootlearn.core.listener.RedisMessageListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;

@Configuration
public class RedisListenerConfiguration {

    @Value("${spring.redis.listen-pattern}")
    public String pattern;

    @Bean
    public RedisMessageListenerContainer listenerContainer(RedisConnectionFactory redisConnection) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnection);

        /**
         * Topic是消息发布(Pub)者和订阅(Sub)者之间的传输中介
         */
        Topic topic = new PatternTopic(this.pattern);

        container.addMessageListener(new RedisMessageListener(), topic);
        return container;
    }
}
  • Redis 事件广播监听器
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

public class RedisMessageListener implements MessageListener {

    /**
     * Redis 事件监听回调
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] body = message.getBody();

        String expiredKey = new String(body);

        System.out.println("监听到已过期的key:" + expiredKey);

        /**
         * 监听到过期事件回调
         * TODO:
         */

    }
}
  • 测试接口
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping(value = "/setExpiredVal")
    public String setExpiredVal(@RequestParam String name) {
    	// 设置 20s 后过期
        redisTemplate.opsForValue().set("name", name, 20, TimeUnit.SECONDS);
        return "setVal is ok";
    }

}
  • 访问接口
    在这里插入图片描述
  • 20s后控制台输出如下:
    在这里插入图片描述
  • 接下来就可以去处理相应的业务了。

- End -
- 个人学习笔记 -
- 仅供参考 -

Spring Boot结合Redis实现登录功能通常涉及以下几个步骤: 1. **添加依赖**: 在`pom.xml`添加Spring Data Redis和Spring Security的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. **配置Redis**: 在`application.properties`设置Redis连接信息: ``` spring.redis.host=localhost spring.redis.port=6379 ``` 3. **配置Security**: 创建`SecurityConfig`类,重写WebSecurityConfigurerAdapter,配置Redis作为用户认证存储: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Value("${spring.redis.authKey}") private String authKey; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .defaultSuccessUrl("/") .failureHandler(new CustomAuthenticationFailureHandler()) .and() .logout() .permitAll(); } @Bean public AuthenticationManager authenticationManager() throws Exception { RedisAuthenticationProvider provider = new RedisAuthenticationProvider(); provider.setConnectionFactory(connectionFactory()); provider.setUserDetailsMapper(userDetailsService); return provider; } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); JedisConnectionFactory factory = new JedisConnectionFactory(); factory.setHostName(authKey); //...其他属性配置 template.setConnectionFactory(factory); template.afterPropertiesSet(); return template; } } ``` 4. **用户服务** (`UserDetailsService`实现): 从Redis读取用户的加密密码并验证: ```java @Service public class UserService implements UserDetailsService { private final JdbcTemplate jdbcTemplate; @Autowired public UserService(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //从Redis获取用户信息,比如通过username和hash存储 Map<String, Object> userDetails = jedis.get(username); if (userDetails == null) throw new UsernameNotFoundException("Invalid username"); //解码密码并进一步处理... } } ``` 5. **登录和注销**: 使用Spring Security提供的表单登录功能,用户输入用户名和密码后会自动进行验证。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Maggieq8324

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值