C#连redis

 

引入

 

 Microsoft.Extensions.Caching.Redis其实就是封装了StackExchange.redis

 

控制台例子:

    class Program
    {
        public static void Main()
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379");
            IDatabase db = redis.GetDatabase();
            db.StringSet("name1", "abc");
            var value = db.StringGet("name1");
            Console.WriteLine(value);
            Console.ReadKey();
        }
    }

 

.net core 例子:

    public class WeatherForecastController : ControllerBase
    {

        private IDistributedCache _redisCache;

        public WeatherForecastController(IDistributedCache redisCache)
        {
            _redisCache = redisCache;
        }

        [HttpGet]
        public string Get()
        {
            //将数据放入redis中 
            _redisCache.SetString("name", "zhangsan");
            var value = _redisCache.GetString("name");
            return value;
        }

    }

Startup

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            //配置redis数据库
            services.AddDistributedRedisCache(options =>
            {
                options.InstanceName = "redis";
                options.Configuration = "127.0.0.1:6379";
            });
        }

运行后能得到结果,但是直接用客户端查,查不到该name的值,关掉redis服务器,再用程序读取也读取不到值。暂时不明白。

posted @ 2019-12-04 14:10  富坚老贼  阅读(522)  评论(0编辑  收藏  举报