mirror of
https://gitee.com/dromara/sa-token.git
synced 2025-07-19 07:44:52 +08:00
SaSession.get() 增加缓存API,简化代码
This commit is contained in:
parent
34a62a2aa0
commit
a54a8cc455
@ -0,0 +1,18 @@
|
|||||||
|
package cn.dev33.satoken.fun;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设定一个函数,并返回一个值,方便在Lambda表达式下的函数式编程
|
||||||
|
* @author kong
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public interface SaRetFunction {
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行的方法
|
||||||
|
* @return 返回值
|
||||||
|
*/
|
||||||
|
public Object run();
|
||||||
|
|
||||||
|
|
||||||
|
}
|
@ -8,6 +8,7 @@ import java.util.Vector;
|
|||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
import cn.dev33.satoken.SaManager;
|
import cn.dev33.satoken.SaManager;
|
||||||
|
import cn.dev33.satoken.fun.SaRetFunction;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Session Model
|
* Session Model
|
||||||
@ -325,6 +326,24 @@ public class SaSession implements Serializable {
|
|||||||
return getValueByDefaultValue(get(key), defaultValue);
|
return getValueByDefaultValue(get(key), defaultValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* 取值 (如果值为null,则执行fun函数获取值)
|
||||||
|
* @param <T> 返回值的类型
|
||||||
|
* @param key key
|
||||||
|
* @param fun 值为null时执行的函数
|
||||||
|
* @return 值
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public <T> T get(String key, SaRetFunction fun) {
|
||||||
|
Object value = get(key);
|
||||||
|
if(value == null) {
|
||||||
|
value = fun.run();
|
||||||
|
set(key, value);
|
||||||
|
}
|
||||||
|
return (T) value;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 取值 (转String类型)
|
* 取值 (转String类型)
|
||||||
* @param key key
|
* @param key key
|
||||||
|
@ -241,7 +241,20 @@ public class TestController {
|
|||||||
@RequestMapping("test")
|
@RequestMapping("test")
|
||||||
public AjaxJson test() {
|
public AjaxJson test() {
|
||||||
System.out.println("进来了");
|
System.out.println("进来了");
|
||||||
System.out.println(StpUtil.getTokenInfo());
|
// System.out.println(StpUtil.getTokenInfo());
|
||||||
|
StpUtil.setLoginId(10001);
|
||||||
|
String ss = StpUtil.getSession().get("name", () -> {
|
||||||
|
System.out.println("-=------进入方法");
|
||||||
|
return "zhangsan";
|
||||||
|
});
|
||||||
|
ss = StpUtil.getSession().get("name", () -> {
|
||||||
|
System.out.println("-=------进入方法2");
|
||||||
|
return "zhangsan2";
|
||||||
|
});
|
||||||
|
|
||||||
|
StpUtil.getSession().delete("name");
|
||||||
|
System.out.println(ss);
|
||||||
|
|
||||||
return AjaxJson.getSuccess("访问成功");
|
return AjaxJson.getSuccess("访问成功");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user