SaSession.get() 增加缓存API,简化代码

This commit is contained in:
shengzhang 2021-05-24 22:42:50 +08:00
parent 34a62a2aa0
commit a54a8cc455
3 changed files with 51 additions and 1 deletions

View File

@ -0,0 +1,18 @@
package cn.dev33.satoken.fun;
/**
* 设定一个函数并返回一个值方便在Lambda表达式下的函数式编程
* @author kong
*
*/
public interface SaRetFunction {
/**
* 执行的方法
* @return 返回值
*/
public Object run();
}

View File

@ -8,6 +8,7 @@ import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.fun.SaRetFunction;
/**
* Session Model
@ -325,6 +326,24 @@ public class SaSession implements Serializable {
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类型)
* @param key key

View File

@ -241,7 +241,20 @@ public class TestController {
@RequestMapping("test")
public AjaxJson test() {
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("访问成功");
}