Flutter会话管理插件pip_services_sessions的使用
Flutter会话管理插件pip_services_sessions的使用

Sessions Microservice
这是来自Pip.Services库的用户会话微服务。它打开和关闭用户会话,并存储会话数据。
该微服务目前支持以下部署选项:
- 部署平台:独立进程、Seneca
- 外部API:HTTP/REST、Seneca
- 持久化:扁平文件、MongoDB
该微服务不依赖于其他微服务。
合同
以下是微服务的逻辑合同。对于物理实现(HTTP/REST),请参阅特定协议的文档。
class SessionV1 implements IStringIdentifiable {
/* Identification */
String id;
String user_id;
String user_name;
/* Session info */
bool active;
DateTime open_time;
DateTime close_time;
DateTime request_time;
String address;
String client;
/* Cached content */
var user;
var data;
}
abstract class ISessionsV1 {
Future<DataPage<SessionV1>> getSessions(
String correlationId, FilterParams filter, PagingParams paging);
Future<SessionV1> getSessionById(String correlationId, String id);
Future<SessionV1> openSession(
String correlationId,
String user_id,
String user_name,
String address,
String client,
dynamic user,
dynamic data);
Future<SessionV1> storeSessionData(String correlationId, String sessionId, dynamic data);
Future<SessionV1> updateSessionUser(String correlationId, String sessionId, dynamic user);
Future<SessionV1> closeSession(String correlationId, String sessionId);
Future<SessionV1> deleteSessionById(String correlationId, String sessionId);
}
下载
目前,唯一获取微服务的方式是从GitHub仓库直接克隆。
git clone git@github.com:pip-services-users/pip-services-sessions-dart.git
Pip.Service团队正在努力实现打包,并使其稳定发布可以作为可下载的zip归档提供。
运行
在微服务文件夹的根目录下添加config.yaml
文件并设置配置参数。
微服务配置示例:
---
# 容器描述符
- descriptor: "pip-services:context-info:default:default:1.0"
name: "pip-services-sessions"
description: "Sessions microservice for pip-services"
# 控制台日志记录器
- descriptor: "pip-services:logger:console:default:1.0"
level: "trace"
# 性能计数器,将值发布到日志
- descriptor: "pip-services:counters:log:default:1.0"
level: "trace"
{{#MEMORY_ENABLED}}
# 内存持久化。仅用于测试!
- descriptor: "pip-services-sessions:persistence:memory:default:1.0"
{{/MEMORY_ENABLED}}
{{#FILE_ENABLED}}
# 文件持久化。用于测试或简单的独立部署
- descriptor: "pip-services-sessions:persistence:file:default:1.0"
path: {{FILE_PATH}}{{^FILE_PATH}}"./data/sessions.json"{{/FILE_PATH}}
{{/FILE_ENABLED}}
{{#MONGO_ENABLED}}
# MongoDB持久化
- descriptor: "pip-services-sessions:persistence:mongodb:default:1.0"
collection: {{MONGO_COLLECTION}}{{^MONGO_COLLECTION}}sessions{{/MONGO_COLLECTION}}
connection:
uri: {{{MONGO_SERVICE_URI}}}
host: {{{MONGO_SERVICE_HOST}}}{{^MONGO_SERVICE_HOST}}localhost{{/MONGO_SERVICE_HOST}}
port: {{MONGO_SERVICE_PORT}}{{^MONGO_SERVICE_PORT}}27017{{/MONGO_SERVICE_PORT}}
database: {{MONGO_DB}}{{#^MONGO_DB}}app{{/^MONGO_DB}}
credential:
username: {{MONGO_USER}}
password: {{MONGO_PASS}}
{{/MONGO_ENABLED}}
{{^MEMORY_ENABLED}}{{^FILE_ENABLED}}{{^MONGO_ENABLED}}
# 默认的内存持久化
- descriptor: "pip-services-sessions:persistence:memory:default:1.0"
{{/MONGO_ENABLED}}{{/FILE_ENABLED}}{{/MEMORY_ENABLED}}
# 默认控制器
- descriptor: "pip-services-sessions:controller:default:default:1.0"
# 公共HTTP端点
- descriptor: "pip-services:endpoint:http:default:1.0"
connection:
protocol: "http"
host: "0.0.0.0"
port: 8080
# HTTP端点版本1.0
- descriptor: "pip-services-sessions:service:http:default:1.0"
# 心跳服务
- descriptor: "pip-services:heartbeat-service:http:default:1.0"
# 状态服务
- descriptor: "pip-services:status-service:http:default:1.0"
有关微服务配置的更多信息,请参阅配置指南。
启动微服务使用命令:
dart ./bin/run.dart
使用
使用微服务最简单的方法是使用客户端SDK。不同语言可用的客户端SDK列表见快速链接部分。
如果你使用Dart,那么需要引用所需的库:
- Pip.Services3.Commons: https://github.com/pip-services3-dart/pip-services3-commons-dart
- Pip.Services3.Rpc: https://github.com/pip-services3-dart/pip-services3-rpc-dart
添加pip-services3-commons-dart
,pip-services3-rpc-dart
和pip-services_sessions
包:
import 'package:pip_services3_commons/pip_services3_commons.dart';
import 'package:pip_services3_rpc/pip_services3_rpc.dart';
import 'package:pip_services_sessions/pip_services_sessions.dart';
定义与微服务外部API匹配的客户端配置参数:
// 客户端配置
var httpConfig = ConfigParams.fromTuples(
"connection.protocol", "http",
"connection.host", "localhost",
"connection.port", 8080
);
实例化客户端并连接到微服务:
// 创建客户端实例
var client = SessionsHttpClientV1(config);
// 配置客户端
client.configure(httpConfig);
// 连接到微服务
try {
await client.open(null);
} catch (err) {
// 错误处理...
}
// 与微服务交互
// ...
现在客户端已准备好执行操作:
// 打开新会话
try {
var session1 = await client.openSession('123', '1', 'User 1', 'localhost', 'test', 'abc');
// 对返回的会话进行操作...
} catch (err) {
// 错误处理...
}
获取会话:
try {
var session = await client.getSessionById(
null,
session1.id);
// 对会话进行操作...
} catch (err) {
// 错误处理...
}
示例
以下是会话微服务的示例。
定义与微服务外部API匹配的配置参数:
// 服务/客户端配置
var httpConfig = ConfigParams.fromTuples(
"connection.protocol", "http",
"connection.host", "localhost",
"connection.port", 8080
);
实例化服务:
persistence = SessionsMemoryPersistence();
persistence.configure(ConfigParams());
controller = SessionsController();
controller.configure(ConfigParams());
service = SessionsHttpServiceV1();
service.configure(httpConfig);
var references = References.fromTuples([
Descriptor('pip-services-sessions', 'persistence', 'memory',
'default', '1.0'),
persistence,
Descriptor('pip-services-sessions', 'controller', 'default',
'default', '1.0'),
controller,
Descriptor(
'pip-services-sessions', 'service', 'http', 'default', '1.0'),
service
]);
controller.setReferences(references);
service.setReferences(references);
await persistence.open(null);
await service.open(null);
实例化客户端并连接到微服务:
// 创建客户端实例
var client = SessionsHttpClientV1(config);
// 配置客户端
client.configure(httpConfig);
// 连接到微服务
try {
await client.open(null);
} catch (err) {
// 错误处理...
}
// 与微服务交互
// ...
现在客户端已准备好执行操作:
// 打开新会话
try {
var session1 = await client.openSession('123', '1', 'User 1', 'localhost', 'test', 'abc');
// 对返回的会话进行操作...
} catch (err) {
// 错误处理...
}
获取会话:
try {
var session = await client.getSessionById(
null,
session1.id);
// 对会话进行操作...
} catch (err) {
// 错误处理...
}
更多关于Flutter会话管理插件pip_services_sessions的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter会话管理插件pip_services_sessions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
pip_services_sessions
是一个用于在 Flutter 应用中管理会话的插件。它提供了一种简单的方式来处理会话数据,如用户认证、会话存储和会话过期等。以下是如何在 Flutter 项目中使用 pip_services_sessions
插件的基本步骤。
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 pip_services_sessions
插件的依赖。
dependencies:
flutter:
sdk: flutter
pip_services_sessions: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来安装依赖。
2. 初始化会话管理器
在你的 Flutter 应用中,你需要初始化一个会话管理器。通常,你可以在 main.dart
文件中完成这个操作。
import 'package:pip_services_sessions/pip_services_sessions.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 初始化会话管理器
var sessionManager = SessionManager();
await sessionManager.configure(ConfigParams.fromTuples([
'store.type', 'memory', // 使用内存存储,你也可以使用其他存储类型
'timeout', 3600 // 会话超时时间,单位为秒
]));
runApp(MyApp(sessionManager: sessionManager));
}
3. 使用会话管理器
在你的应用程序中,你可以使用会话管理器来创建、获取和删除会话。
class MyApp extends StatelessWidget {
final SessionManager sessionManager;
MyApp({required this.sessionManager});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Session Management Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () async {
// 创建一个新会话
var session = await sessionManager.createSession('user123', 'user');
print('Session created: ${session.id}');
},
child: Text('Create Session'),
),
ElevatedButton(
onPressed: () async {
// 获取会话
var session = await sessionManager.getSession('sessionId');
if (session != null) {
print('Session found: ${session.id}');
} else {
print('Session not found');
}
},
child: Text('Get Session'),
),
ElevatedButton(
onPressed: () async {
// 删除会话
await sessionManager.deleteSession('sessionId');
print('Session deleted');
},
child: Text('Delete Session'),
),
],
),
),
),
);
}
}
4. 处理会话过期
会话管理器会自动处理会话的过期。你可以通过配置 timeout
参数来设置会话的过期时间。当会话过期时,会话管理器会自动删除该会话。
5. 使用不同的存储类型
pip_services_sessions
支持多种存储类型,如内存、文件、数据库等。你可以通过在配置中指定 store.type
来使用不同的存储类型。
await sessionManager.configure(ConfigParams.fromTuples([
'store.type', 'file', // 使用文件存储
'store.path', '/sessions', // 文件存储路径
'timeout', 3600 // 会话超时时间,单位为秒
]));
6. 处理错误
在使用会话管理器时,可能会遇到各种错误,如会话不存在、存储错误等。你可以通过捕获异常来处理这些错误。
try {
var session = await sessionManager.getSession('invalidSessionId');
if (session != null) {
print('Session found: ${session.id}');
} else {
print('Session not found');
}
} catch (e) {
print('Error: $e');
}