尝试通过 ServiceStack.Redis 读取 redis 列表时,我间歇性地收到以下错误:“无法从传输连接读取数据:已建立的连接被主机中的软件中止”。我想知道我关于如何使用 ServiceStack 可靠地连接和池连接到 Redis 的整个概念是否错误。这是我使用密封类和单例模式进行连接的代码:
public sealed class RedisClientBase
{
public BasicRedisClientManager Redis;
private static readonly RedisClientBase instance = new RedisClientBase();
private RedisClientBase()
{
Redis = new BasicRedisClientManager("mypassword@localhost:6379");
}
public static RedisClientBase Instance
{
get
{
return instance;
}
}
}
然后我实例化另一个使用单例的类:
public class RedisBarSetData
{
private static RedisClient Redis;
protected IRedisTypedClient<BarSet> redisBarSetClient;
protected string instrument_key;
public RedisBarSetData()
{
Redis = (RedisClient)RedisClientBase.Instance.Redis.GetClient();
redisBarSetClient = Redis.As<BarSet>();
}
~RedisBarSetData()
{
if (Redis != null)
Redis.Dispose();
}
public List<BarSet> getData(BarSets data)
{
setKeys(data); // instrument_key is set in here
var redisBarSetClientList = redisBarSetClient.Lists[instrument_key];
List<BarSet> barSetData;
barSetData = redisBarSetClientList.GetAll(); // <-- exception here (sometimes)
return(barSetData);
}
}
这又被实例化并从“服务”DTO 回调中调用:
public class JmaSetsService : Service
{
public object Get(JmaSets request)
{
RedisBarSetData barSetData = new RedisBarSetData();
BarSets barSets = new BarSets(request);
barSetList = barSetData.getData(barSets);
return barSetList;
}
}
然后我使用“邮递员”发布到这条路线。大多数点击“发送”都会返回数据。有些以例外结束。例外情况是尝试从 redis 中读取,如代码中带有注释“<-- exception here”的代码中所示。现在还有一点是我最近通过设置配置文件将我的redis配置为使用密码。我提到这一点是因为我不记得以前有过这个问题,但这也可能无关,不知道。
在释放 redis 连接方面,我的想法是当 RedisBarSetData() 超出范围时,我的析构函数调用 Redis.Dispose 。这是处理它的可靠方法还是有更好的方法。我看到人们在获取池客户端时使用“使用”语句,但是我有很多“使用”语句,而不是在课堂上的一个地方调用:“Redis = (RedisClient)RedisClientBase.Instance.Redis .GetClient();" 如果我有一堆类的方法,那么我必须在每个方法中重复代码吗?
- 当我说“我不记得以前有过这个问题”时,我将这种模式用于数十个工作 DTO。不知道为什么它现在失败了?