Modifying the default connection(修改默认连接)
客户端在IConnection之后抽象发送请求并创建响应,默认实现使用System.Net.Http.HttpClient。 您为什么要通过自己的IConnection?让我们看几个例子
Using InMemoryConnectionedit(使用 InMemoryConnectionedit)
InMemoryConnection是一个内置的IConnection,可以轻松编写针对其的单元测试。可以将其配置为使用默认响应字节,HTTP状态代码和调用时的异常进行响应。
InMemoryConnection实际上并没有从Elasticsearch发送任何请求或接收任何响应;如果.DisableDirectStreaming在请求上或全局设置为true,则请求仍会序列化,并且可以在响应上获取请求字节
var connection = new InMemoryConnection();
var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(connectionPool, connection);
var client = new ElasticClient(settings);
|
在这里,我们通过使用带有IConnectionPool和IConnection的重载来创建新的ConnectionSettings。我们为它传递了一个InMemoryConnection,它使用默认的无参数构造函数,将为所有内容返回200,并且从不实际执行任何IO。
我们来看一个更复杂的例子
var response = new
{
took = 1,
timed_out = false,
_shards = new
{
total = 2,
successful = 2,
failed = 0
},
hits = new
{
total = new { value = 25 },
max_score = 1.0,
hits = Enumerable.Range(1, 25).Select(i => (object)new
{
_index = "project",
_type = "project",
_id = $"Project {i}",
_score = 1.0,
_source = new { name = $"Project {i}" }
}).ToArray()
}
};
var responseBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response));
var connection = new InMemoryConnection(responseBytes, 200); ①
var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(connectionPool, connection).DefaultIndex("project");
var client = new ElasticClient(settings);
var searchResponse = client.Search<Project>(s => s.MatchAll());
|
① InMemoryConnection配置为始终返回responseBytes以及200个HTTP状态代码
现在我们可以断言searchResponse有效,并且包含从固定的InMemoryConnection响应中反序列化的文档
Changing HttpConnectionedit(更改HttpConnection)
可能需要更改默认HttpConnection的工作方式,例如,向请求中添加X509证书,更改允许与端点的最大连接数等。
通过从HttpConnection派生,可以更改连接的行为。以下提供一些示例
public class MyCustomHttpConnection : HttpConnection
{
protected override HttpRequestMessage CreateRequestMessage(RequestData requestData)
{
var message = base.CreateRequestMessage(requestData);
var header = string.Empty;
message.Headers.Authorization = new AuthenticationHeaderValue("Negotiate", header);
return message;
}
}
public class KerberosConnection : HttpConnection
{
protected override HttpRequestMessage CreateRequestMessage(RequestData requestData)
{
var message = base.CreateRequestMessage(requestData);
var header = string.Empty;
message.Headers.Authorization = new AuthenticationHeaderValue("Negotiate", header);
return message;
}
}
|
See
Working with certificates for further details.(有关更多详细信息,请参见使用证书。)
标签:InMemoryConnection,default,NEST,03Modifying,connection,HttpConnection,var,new,me
来源: https://www.cnblogs.com/xianchengzhang/p/14629951.html