依赖:
<dependency>
<groupId>com.alipay.sofa</groupId>
<artifactId>jraft-core</artifactId>
<version>1.3.14</version>
</dependency>
StateMachine.java:
@Slf4j
public class StateMachine extends StateMachineAdapter {
private final String name;
public StateMachine(String name) {
this.name = name;
}
@Override
public void onApply(Iterator iterator) {
}
@Override
public void onLeaderStart(long term) {
log.info(name + "become leader");
}
@Override
public void onLeaderStop(Status status) {
log.info(name + "end leader");
}
@Override
public void onStopFollowing(LeaderChangeContext ctx) {
log.info(name + "stop following leader");
}
@Override
public void onStartFollowing(LeaderChangeContext ctx) {
log.info(name + "start following leader");
}
}
主要流程:
public class Main {
public static void main(String[] args) {
int id = Integer.parseInt(args[0]);
List<PeerId> peerIdList = new ArrayList<>();
Configuration conf = new Configuration();
for (int i = 0; i < 2; i++) {
PeerId p = new PeerId("localhost", 6000 + i);
peerIdList.add(p);
conf.addPeer(p);
}
PeerId serverId = peerIdList.get(id);
NodeOptions nodeOptions = new NodeOptions();
nodeOptions.setLogUri("raftLog");
nodeOptions.setRaftMetaUri("raftMeta");
nodeOptions.setInitialConf(conf);
nodeOptions.setFsm(new StateMachine(serverId.toString()));
Node node = RaftServiceFactory.createRaftNode("group", serverId);
NodeManager.getInstance().addAddress(serverId.getEndpoint());
node.init(nodeOptions);
RpcServer rpcServer = RaftRpcServerFactory.createRaftRpcServer(serverId.getEndpoint());
rpcServer.init(null);
}
}
标签:name,选举,JRaft,public,nodeOptions,new,raft,serverId,void From: https://www.cnblogs.com/JackieJK/p/18288772