这个错误是因为 `SecurityClient` 的构造函数不是公共的,不能从包外访问。解决这个问题的方法是使用 `XPackClient` 来创建 `SecurityClient`。
以下是修改后的代码示例:
```java
import org.apache.http.HttpHost;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken;
import org.elasticsearch.xpack.security.client.SecurityClient;
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
import java.net.InetAddress;
import java.util.Collections;
public class CreateUserExample {
public static void main(String[] args) throws Exception {
// 创建 RestHighLevelClient
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建用户名和密码
String username = "testuser";
String password = "testpassword";
// 创建用户请求
SecurityClient securityClient = new PreBuiltXPackTransportClient(Settings.EMPTY)
.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300))
.authenticate(new UsernamePasswordToken(username, password))
.security();
ActionListener listener = new ActionListener() {
@Override
public void onResponse(Void response) {
System.out.println("User created successfully.");
}
@Override
public void onFailure(Exception e) {
System.out.println("Failed to create user: " + e.getMessage());
}
};
securityClient.createUser(username, password.toCharArray(), Collections.singletonList("user"), listener);
// 关闭客户端
client.close();
}
}
```
在上面的示例代码中,我们使用 `PreBuiltXPackTransportClient` 创建了一个新的 `SecurityClient`。然后