HazelCast Spring Boot 集成

SpringBoot集成HazelCast分布式框架

一、HazelCast 简介

Hazelcast提供Java接口的分布式实现,是一款优秀的基于内存的分布式数据网格开源项目,同时也是一家公司的名称。

二、使用SpringBoot 启动 HazelCast

1. 引入Hzaelcast依赖

1
2
3
4
5
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-all</artifactId>
<version>4.1</version>
</dependency>

2.创建控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package icu.debug.hazelcast.springboot;

import com.hazelcast.core.HazelcastInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ConcurrentMap;

@RestController
public class CommandController {
@Autowired
private HazelcastInstance hazelcastInstance;

private ConcurrentMap<String,String> retrieveMap() {
return hazelcastInstance.getMap("map");
}

@PostMapping("/put")
public CommandResponse put(@RequestParam(value = "key") String key, @RequestParam(value = "value") String value) {
retrieveMap().put(key, value);
return new CommandResponse(value);
}

@GetMapping("/get")
public CommandResponse get(@RequestParam(value = "key") String key) {
String value = retrieveMap().get(key);
return new CommandResponse(value);
}
}

3. 启动服务集群

开启多个窗口,分别执行以下命令启动多个服务

1
2
3
4
5
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dserver.port=8080"
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dserver.port=8081"
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dserver.port=8082"
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dserver.port=8083"
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dserver.port=8084"

image-20210606163237418

1
2
3
4
5
6
7

Members {size:4, ver:4} [
Member [192.168.0.239]:5701 - 815c5f76-c03e-48b2-aeef-b71bdfa41251
Member [192.168.0.239]:5702 - 484110d6-8ef9-439b-a2e0-19ff071f1ed3
Member [192.168.0.239]:5703 - 42ee161f-ed64-4406-b054-fb90798bc7ce
Member [192.168.0.239]:5704 - 94f82315-e8c1-4cf0-8945-efd8bd48cb75 this
]

4. 写入并获取数据

1
2
3
4
5
6
7
8
9
10
11
12
PS C:\Users\hajnxg> curl --data "key=key1&value=test1" "localhost:8081/put"
{"value":"test1"}
PS C:\Users\hajnxg>
PS C:\Users\hajnxg>
PS C:\Users\hajnxg> curl "localhost:8085/get?key=key1"
{"value":"test1"}
PS C:\Users\hajnxg> curl "localhost:8082/get?key=key1"
{"value":"test1"}
PS C:\Users\hajnxg> curl "localhost:8080/get?key=key1"
{"value":"test1"}
PS C:\Users\hajnxg> curl "localhost:8081/get?key=key1"
{"value":"test1"}