经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
Dapr在Java中的实践 之 状态管理
来源:cnblogs  作者:万猫学社  时间:2023/6/7 10:11:40  对本文有异议

状态管理

状态管理(State Management)使用键值对作为存储机制,可以轻松的使长时运行、高可用的有状态服务和无状态服务共同运行在我们的服务中。

我们的服务可以利用Dapr的状态管理API在状态存储组件中保存、读取和查询键值对。

状态存储组件是可插拔的,目前支持使用Azure CosmosDB、 Azure SQL Server、 PostgreSQL,、AWS DynamoDB、Redis 作为状态存储介质。

文章持续更新,微信搜索「万猫学社」第一时间阅读,关注后回复「电子书」,免费获取12本Java必读技术书籍。

编写示例代码

创建一个SpringBoot项目,命名为:state-management,该项目的状态管理调用过程如下图:

state-management-overview.png

state-management该项目的pom.xml文件中添加如下依赖:

  1. <dependency>
  2. <groupId>io.dapr</groupId>
  3. <artifactId>dapr-sdk-springboot</artifactId>
  4. <version>1.4.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.squareup.okhttp3</groupId>
  8. <artifactId>okhttp</artifactId>
  9. <version>4.9.3</version>
  10. </dependency>

注入一个DaprClient的bean:

  1. @Configuration
  2. public class DaprConfig {
  3. private static final DaprClientBuilder BUILDER = new DaprClientBuilder();
  4. @Bean
  5. public DaprClient buildDaprClient() {
  6. return BUILDER.build();
  7. }
  8. }

state-management项目中一共有3个接口:

  • save:保存状态
  • get:读取状态
  • delete:删除状态

具体源码如下:

  1. package one.more.society.state.management;
  2. import io.dapr.client.DaprClient;
  3. import io.dapr.client.domain.State;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import org.springframework.web.bind.annotation.RestController;
  9. @Slf4j
  10. @RestController
  11. public class StateManagementController {
  12. @Autowired
  13. private DaprClient client;
  14. private static final String STATE_STORE_NAME = "statestore";
  15. private static final String STATE_STORE_KEY = "one.more.society";
  16. /**
  17. * 保存状态
  18. *
  19. * @param value value
  20. * @return
  21. */
  22. @RequestMapping(value = "/save", method = RequestMethod.GET)
  23. public StateResponse save(String value) {
  24. log.info("save - value:{}", value);
  25. client.saveState(STATE_STORE_NAME, STATE_STORE_KEY, value).block();
  26. StateResponse response = new StateResponse();
  27. response.setCode(1);
  28. response.setStatus("save");
  29. response.setValue(value);
  30. return response;
  31. }
  32. /**
  33. * 读取状态
  34. *
  35. * @return StateResponse
  36. */
  37. @RequestMapping(value = "/get", method = RequestMethod.GET)
  38. public StateResponse get() {
  39. log.info("get");
  40. State<String> value = client.getState(STATE_STORE_NAME, STATE_STORE_KEY, String.class).block();
  41. log.info("value: {}", value.getValue());
  42. StateResponse response = new StateResponse();
  43. response.setCode(1);
  44. response.setStatus("get");
  45. response.setValue(value.getValue());
  46. return response;
  47. }
  48. /**
  49. * 删除状态
  50. *
  51. * @return
  52. */
  53. @RequestMapping(value = "/delete", method = RequestMethod.GET)
  54. public StateResponse delete() {
  55. log.info("delete");
  56. client.deleteState(STATE_STORE_NAME, STATE_STORE_KEY).block();
  57. StateResponse response = new StateResponse();
  58. response.setCode(1);
  59. response.setStatus("delete");
  60. return response;
  61. }
  62. }

另外,在application.properties中配置:

  1. server.port=30003

文章持续更新,微信搜索「万猫学社」第一时间阅读,关注后回复「电子书」,免费获取12本Java必读技术书籍。

启动服务

在启动之前先用mvn命令打包:

  1. mvn clean package

state-management项目的目录中执行以下命令,启动state-management服务:

  1. dapr run --app-id state-management --app-port 30003 --dapr-http-port 31003 -- java -jar target/state-management-0.0.1-SNAPSHOT.jar

在Dapr Dashboard中看到:

Dapr Dashboard

服务都已经启动成功。

先访问http://localhost:30003/get,可以看到:

读取状态返回为null,接下来访问http://localhost:30003/save?value=万猫学社,可以看到:

状态已经保存了,再访问http://localhost:30003/get验证一下:

状态被正确读取,再访问http://localhost:30003/delete,可以看到:

状态已经被删除了,再访问http://localhost:30003/get验证一下:

读取状态返回为null。

文章持续更新,微信搜索「万猫学社」第一时间阅读,关注后回复「电子书」,免费获取12本Java必读技术书籍。

状态储存组件

初始化Dapr后,默认为我们指定的状态储存组件是Redis,在用户目录下的.dapr文件夹中的components文件夹中,可以找到statestore.yaml文件:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: statestore
  5. spec:
  6. type: state.redis
  7. version: v1
  8. metadata:
  9. - name: redisHost
  10. value: localhost:6379
  11. - name: redisPassword
  12. value: ""
  13. - name: actorStateStore
  14. value: "true"

下面让我们来尝试一下,使用MySQL作为状态储存组件,把statestore.yaml文件修改为:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: statestore
  5. spec:
  6. type: state.mysql
  7. version: v1
  8. metadata:
  9. - name: connectionString
  10. value: "root:one.more.society@tcp(127.0.0.1:3306)/?allowNativePasswords=true"

重新启动服务,可以看到在日志中看到使用MySQL作为状态储存组件:

  1. time="09:57:35.5632633+08:00" level=info msg="Creating MySql schema 'dapr_state_store'" app_id=state-management instance=JT-243137 scope=dapr.contrib type=log ver=1.7.3
  2. time="09:57:35.5862126+08:00" level=info msg="Creating MySql state table 'state'" app_id=state-management instance=JT-243137 scope=dapr.contrib type=log ver=1.7.3
  3. time="09:57:35.6563599+08:00" level=info msg="component loaded. name: statestore, type: state.mysql/v1" app_id=state-management instance=JT-243137 scope=dapr.runtime type=log ver=1.7.3

如果在MySQL中没有对应的库和表,Dapr默认为我们自动创建一个名为dapr_state_store的库,还有一个名为state的表,如下图:

其中,state的表结构为:

  1. CREATE TABLE `state` (
  2. `id` varchar(255) NOT NULL,
  3. `value` json NOT NULL,
  4. `isbinary` tinyint(1) NOT NULL,
  5. `insertDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  6. `updateDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  7. `eTag` varchar(36) NOT NULL,
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

再访问一下http://localhost:30003/save?value=万猫学社,就可以在数据库中看到对应的数据:

值得注意的是:MySQL状态储存组件目前还处于Alpha状态,最好不要在生产环境使用。

更详细的配置说明见下表:

配置项 是否必填 说明 示例
connectionString Y 用于连接到 MySQL 的连接字符串。 请不要将schema添加到连接字符串中。 非SSL连接:
"<user>:<password>@tcp(<server>:3306)/?allowNativePasswords=true"
Enforced SSL 连接:
"<user>:<password>@tcp(<server>:3306)/?allowNativePasswords=true&tls=custom"
schemaName N 要使用的schema名称。 如果指定的schema不存在,将会自动创建。默认值为"dapr_state_store" "one_more_state_store"
tableName N 要使用的表名。如果对应的表不存在,将被自动创建。默认值为 "state" "one_more_state"
pemPath N 使用 Enforced SSL 连接 时,指定要使用的 PEM 文件完整路径。 "/one/more/society/file.pem"
pemContents N 如果没有提供pemPath,用于Enforced SSL连接的PEM文件的内容。可以在K8s环境下使用。 "pem value"

配置示例:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: statestore
  5. spec:
  6. type: state.mysql
  7. version: v1
  8. metadata:
  9. - name: connectionString
  10. value: "root:one.more.society@tcp(127.0.0.1:3306)/?allowNativePasswords=true&tls=custom"
  11. - name: schemaName
  12. value: "one_more_state_store"
  13. - name: tableName
  14. value: "one_more_state"
  15. - name: pemPath
  16. value: "/one/more/society/file.pem"

微信公众号:万猫学社

微信扫描二维码

关注后回复「电子书」

获取12本Java必读技术书籍

原文链接:https://www.cnblogs.com/heihaozi/p/17462287.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号