小程序项目中用户下线不好直接确定
分析:小程序10s请求一次心跳接口,心跳接口激活redis key key过期时间设置为50s,如果我们能在key过期时收到一个通知,就可以确定用户已经下线,便于下线的业务逻辑处理。
准备工作:使用redis key过期通知功能(默认关闭),需要手动在redis-cli中开启。
config set notify-keyspace-events Ex
客户端监听测试:
PSUBSCRIBE __keyevent@*__:expired
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "__keyevent@*__:expired"
3) (integer) 1
项目中实现:
- 添加配置依赖
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- redis pool -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
- 配置redis
spring:
redis:
host: 127.0.0.1
port: 6379
password: test
database: 1
jedis:
pool:
max-active: 8 #最大连接数
max-idle: 8 #最大空闲
min-idle: 5 #最小空闲
timeout: 1000 #连接超时时间
- 消息通知bean配置
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.RedisMessageListenerContainer;
@Configuration
public class BeanInitialization {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}
}
- 过期监听器配置
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
String expiredKey = message.toString();
if (expiredKey.startsWith("test")) {
System.out.println(expiredKey);
}
}
}
总结:
通过redis key过期通知实现用户下线,有效的实现了用户下线的判定,优化了之前通过轮询判断的资源消耗。此功能还可以在订单过期等其他领域中发挥作用。