gpt4 book ai didi

java - 如何对 Set 进行分片?

转载 作者:行者123 更新时间:2023-11-30 01:57:24 24 4
gpt4 key购买 nike

你能帮我做一件事吗?想象一下,我有一个简单的 RESTful 微服务器,其中有一个 GET简单地用随机响应 String 的方法.

我将所有字符串组装在 ConcurrentHashSet<String> 中包含所有答案。

下面有一个草率的实现,主要是Set<String>是一个故障安全装置,可以同时修改。

@RestController
public class Controller {

private final StringService stringService;

private final CacheService cacheService;

public Controller(final StringService stringService, final CacheService cacheService) {
this.stringService = stringService;
this.cacheService = cacheService;
}

@GetMapping
public String get() {
final String str = stringService.random();
cacheService.add(str);
return str;
}

}


public class CacheService {

private final Set<String> set = ConcurrentHashMap.newKeySet();

public void add(final String str) {
set.add(str);
}

}

当您阅读这句话时,我的 endpint 正在被 10 亿人使用。我想对缓存进行分片。由于我的系统负载很重,我无法在一台服务器上保存所有字符串。我想要拥有 256 个服务器/实例并利用 str.hashCode()%256 均匀分布我的缓存函数来确定每个服务器/实例上应该保留一个字符串。

你能告诉我接下来应该做什么吗?假设目前我只在本地运行 Spring Boot 应用程序。

最佳答案

您应该查看Hazelcast ,它是开源的,并且在我想要在应用程序的多个实例之间共享数据的情况下证明对我很有用。 hazelcast 提供的内存数据网格可能正是您正在寻找的东西。

关于java - 如何对 Set 进行分片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53926257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com