我创建了新的asp.net核心项目,我决定使用Cassandra作为数据库,但我以前从未这样做过。我不知道我的做法是否正确?你能给我一些建议,在.net核心中使用这个数据库。 (我使用autofac作为依赖注入容器,cassandra提供者:CassandraCSharpDriver)
我目前的解决方案:
创建群集:
cluster = Cluster.Builder()
.AddContactPoint(cassandraData.ContactPoint)
.WithPort(int.Parse(cassandraData.Port))
.WithCredentials(cassandraData.User, cassandraData.Password)
.Build();
之后我通过依赖注入将其注入我的会话缓存:
public CassandraSessionCache(Cluster cluster)
{
_cluster = cluster;
_sessions = new ConcurrentDictionary<string, Lazy<ISession>>();
}
public ISession GetSession(string keyspaceName)
{
if (!_sessions.ContainsKey(keyspaceName))
_sessions.GetOrAdd(keyspaceName, key => new Lazy<ISession>(() =>
_cluster.Connect(key)));
var result = _sessions[keyspaceName];
return result.Value;
}
我也创建Map到Cassandra并将其用于我的启动课程。
在此配置之后,我的存储库看起来像这样:
public class TestRepository : ITestRepository
{
private readonly CassandraSessionCache _cassandra;
private Mapper _mapper;
public TestRepository(CassandraSessionCache cassandra)
{
_cassandra = cassandra;
}
public async Task DeleteAsync(Guid id, string keySpace)
{
SetSessionAndMapper(keySpace);
await _mapper.DeleteAsync<Test>("WHERE id = ?", id);
}
public async Task<Install> GetAsync(string id, string keySpace)
{
SetSessionAndMapper(keySpace);
return await _mapper.FirstOrDefaultAsync<Test>("SELECT * FROM \"Test\" WHERE id = ?", id);
}
public async Task PostAsync(Test data, string keySpace)
{
SetSessionAndMapper(keySpace);
await _mapper.InsertAsync(data);
}
private void SetSessionAndMapper(string keySpace)
{
var session = _cassandra.GetSession(keySpace);
_mapper = new Mapper(session);
}
}
一切都正确或我做错了什么?