本地测试,暂无 redis,又不想每次重新 run 之后都去登录(SaToken 默认是存到内存中的)。
LocalFileSaTokenDao .kt:
@Component
class LocalFileSaTokenDao : SaTokenDaoDefaultImpl(), ApplicationListener<ContextClosedEvent> {
companion object {
const val DATA_FILE_PATH = "build/sa-token-data.txt"
const val EXPIRE_FILE_PATH = "build/sa-token-expire.txt"
}
@PostConstruct
fun myInit() {
val file = File(DATA_FILE_PATH)
if (file.exists()) {
ObjectInputStream(file.inputStream()).use {
while (true) {
try {
val key = it.readObject() as String
val value = it.readObject() as Any
dataMap[key] = value
} catch (e: EOFException) {
break
}
}
}
}
val expireFile = File(EXPIRE_FILE_PATH)
if (expireFile.exists()) {
ObjectInputStream(expireFile.inputStream()).use {
while (true) {
try {
val key = it.readObject() as String
val value = it.readObject() as Long
expireMap[key] = value
} catch (e: EOFException) {
break
}
}
}
}
}
override fun onApplicationEvent(event: ContextClosedEvent) {
val dataFile = File(DATA_FILE_PATH)
ObjectOutputStream(dataFile.outputStream()).use {
dataMap.forEach { (t, u) ->
it.writeObject(t)
it.writeObject(u)
}
}
val expireFile = File(EXPIRE_FILE_PATH)
ObjectOutputStream(expireFile.outputStream()).use {
expireMap.forEach { (t, u) ->
it.writeObject(t)
it.writeObject(u)
}
}
}
}