会话上下文
1.概述
Ignite 可以在运行时设置自定义应用属性。这些属性可能包括会话ID、应用语言、应用名等。这些属性仅由应用为 Ignite API 入口(Ignite、JDBC)设置一次,然后就可以在所有涉及节点上用于请求处理和查询。
2.SessionContext接口
SessionContext是访问各级属性及其他会话级数据的入口,访问 SessionContext 需要用SessionContextProviderResource注释。用户自定义函数,如 QuerySqlFunction 和 CacheInterceptor,可以通过 SessionContextProvider 访问这些属性。
java
/** SessionContext interface. It's an entrypoint for all attributes. */
public interface SessionContext {
/** @return Attribute by name. */
public @Nullable String getAttribute(String attrName);
}3.QuerySqlFunction中的应用属性
用户自定义的SQL函数QuerySqlFunction,可以使用客户端设置的应用属性:
java
public class MyFunctions {
@SessionContextProviderResource
public SessionContextProvider sesCtxProv;
@QuerySqlFunction
public String sessionId() {
return sesCtxProv.getSessionContext().getAttribute("SESSION_ID");
}
}注意
只有Calcite引擎才能访问应用属性,这时该类必须有一个公开的无参数的构造器。
4.CacheInterceptor中的应用属性
可以配置自定义CacheInterceptor代码,并在回调函数中访问应用属性,这些回调会在主缓存操作前/后被调用:
java
public class SessionContextCacheInterceptor implements CacheInterceptor<Integer, String> {
/** */
@SessionContextProviderResource
private SessionContextProvider sesCtxPrv;
/** */
@Override public @Nullable String onGet(Integer key, @Nullable String val) {
String ret = sesCtxPrv.getSessionContext().getAttribute("onGet");
return ret == null ? val : ret + key;
}
/** */
@Override public @Nullable String onBeforePut(Cache.Entry<Integer, String> entry, String newVal) {
String ret = sesCtxPrv.getSessionContext().getAttribute("onBeforePut");
return ret == null ? newVal : ret + entry.getKey();
}
/** */
@Override public @Nullable IgniteBiTuple<Boolean, String> onBeforeRemove(Cache.Entry<Integer, String> entry) {
String ret = sesCtxPrv.getSessionContext().getAttribute("onBeforeRemove");
return new IgniteBiTuple<>(ret != null, entry.getValue());
}
}5.设置应用属性
5.1.Ignite
可以用Ignite.withApplicationAttributes(…)来设置属性。它返回一个Ignite实例,并持有这些属性,然后会传播到远端节点:
java
try (Ignite ign = Ignition.start(ignCfg)) {
Map<String, String> appAttrs = F.asMap("SESSION_ID", "1234");
Ignite app = Ignite.withApplicationAttributes(appAttrs);
//Your code here...
}5.2.JDBC
标准JDBC协议提供了设置客户端属性的Connection.setClientInfo(…)方法,这些属性在连接生命周期内有效。属性可以通过再次调用Connection.setClientInfo(…)并添加新参数来覆盖:
java
// JDBC connection to Ignite server.
try (Connection conn = DriverManager.getConnection(URL)) {
conn.setClientInfo("SESSION_ID", "1234");
//Your code here...
}18624049226
