Git Product home page Git Product logo

stackexchange.redis.extensions's Introduction

StackExchange.Redis.Extensions

StackExchange.Redis.Extensions is a library that extends StackExchange.Redis allowing you a set of functionality needed by common applications. The library is signed and completely compatible with the .Net Standard 2.0

What can it be used for?

Caching of course. Instead of use directly StackExchange.Redis could be easier use ICacheClient

For example:

  • Add an object to Redis;
  • Custom Serialized (need to implement your own serializer inherit from ISerializer);
  • Changed Flush method;
  • Remove an object from Redis;
  • Search Keys into Redis;
  • Retrieve multiple object with a single roundtrip;
  • Store multiple object with a single roundtrip;
  • Get Redis Server information;
  • Set Add;
  • Set AddAdd;
  • SetRemove;
  • SetRemoveAll;
  • Set Member;
  • Pub/Sub events;
  • Save;
  • Async methods;
  • Hash methods;
  • Support for Keyspace isolation;
  • Much more;
Channel Status
Appveyor CI (Windows) Build status
Travis CI (Linux) Build Status
Nuget (Core) NuGet Status
Nuget (Json.NET) NuGet Status
Nuget (MsgPack) NuGet Status
Nuget (Protobuf) NuGet Status
Nuget (UTF8Json) NuGet Status
Nuget (Binary) NuGet Status

How to install it

StackExchange.Redis.Extensions is composed by two libraries, the Core and the Serializer implementation. Because there are several good serializer and we don't want add another dependency in your project you can choose your favorite or create a new one.

Install Core

PM> Install-Package StackExchange.Redis.Extensions.Core

Install Json.NET implementation

PM> Install-Package StackExchange.Redis.Extensions.Newtonsoft

Install Jil implementation

PM> Install-Package StackExchange.Redis.Extensions.Jil

Install Message Pack CLI implementation

PM> Install-Package StackExchange.Redis.Extensions.MsgPack

Install Protocol Buffers implementation

PM> Install-Package StackExchange.Redis.Extensions.Protobuf 

Install Binary Formatter implementation

PM> Install-Package StackExchange.Redis.Extensions.Binary 

Install UTF8Json Formatter implementation

PM> Install-Package StackExchange.Redis.Extensions.Utf8Json 

How to configure it

You can use it registering the instance with your favorite Container. Here an example using Castle Windsor:

About the configuration is enough to create an instance of RedisConfiguration

var redisConfiguration = new RedisConfiguration()
{
	AbortOnConnectFail = true,
	KeyPrefix = "_my_key_prefix_",
	Hosts = new RedisHost[]
	{
		new RedisHost(){Host = "192.168.0.10", Port = 6379},
		new RedisHost(){Host = "192.168.0.11",  Port =6379},
		new RedisHost(){Host = "192.168.0.12",  Port =6379}
	},
	AllowAdmin = true,
	ConnectTimeout = 3000,
	Database = 0,
	Ssl = true,
	Password = "my_super_secret_password",
	ServerEnumerationStrategy = new ServerEnumerationStrategy()
	{
		Mode = ServerEnumerationStrategy.ModeOptions.All,
		TargetRole = ServerEnumerationStrategy.TargetRoleOptions.Any,
		UnreachableServerAction = ServerEnumerationStrategy.UnreachableServerActionOptions.Throw
	}
};

of course some of them are options (take a look here)

if you are running this library on ASP.NET Core, you can use the following code:

config.SetBasePath(env.ContentRootPath)
.AddJsonFile("./Configuration/appSettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"./Configuration/appSettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();

IConfigurationRoot cfg = config.Build();

var redisConfiguration = cfg.GetSection("Redis").Get<RedisConfiguration>();

here the json file

{
	"Redis": {
		"Password": "my_super_secret_password",
		"AllowAdmin": true,
		"Ssl": false,
		"ConnectTimeout": 6000,
		"ConnectRetry": 2,
		"Database": 0,
		"Hosts": [
		{
			"Host": "192.168.0.10",
			"Port": "6379"
		},
		{
			"Host": "192.168.0.11",
			"Port": "6381"
		}]
	}
}

In case of App.Config or Web.Config you have to use a specific package that reads the configuration from the "old" configuration file.

PM> Install-Package StackExchange.Redis.Extensions.LegacyConfiguration

Here the example of an App.config file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<configSections>
		<section name="redisCacheClient" type="StackExchange.Redis.Extensions.LegacyConfiguration.RedisCachingSectionHandler, StackExchange.Redis.Extensions.LegacyConfiguration" />
	</configSections>

	<redisCacheClient allowAdmin="true" ssl="false" connectTimeout="3000" database="24">
		<serverEnumerationStrategy mode="Single" targetRole="PreferSlave" unreachableServerAction="IgnoreIfOtherAvailable" /> 
		<hosts>
			<add host="127.0.0.1" cachePort="6379" />
		</hosts>
	</redisCacheClient>

</configuration>

after that, to have the configuration, is enough to run this code

var redisConfiguration = RedisCachingSectionHandler.GetConfig();

With dependency Injection you can do something like this using Castle Windsor

container.Register(Component.For<ISerializer>()
				.ImplementedBy<NewtonsoftSerializer>()
				.LifestyleSingleton());

container.Register(Component.For<ICacheClient>()
				.ImplementedBy<StackExchangeRedisCacheClient>()
				.LifestyleSingleton());

or using ASP.NET Core integrated DI:

services.AddSingleton(redisConfiguration);
services.AddSingleton<ICacheClient,StackExchangeRedisCacheClient>();
services.AddSingleton<ISerializer,NewtonsoftSerializer>();

of you can create your own instance

var serializer = new NewtonsoftSerializer();
var cacheClient = new StackExchangeRedisCacheClient(serializer, redisConfiguration);

Serialization

In order to store a class into Redis, that class must be serializable. Below is the list of serialization options:

  • BinaryFormatter - Requires SerializableAttribute on top of the class to store into Redis.
  • Jil - Fastest JSON serializer.
  • MessagePack CLI - serialization/deserialization for CLI.
  • Newtonsoft - Uses Json.Net to serialize a class without SerializableAttribute.
  • Protocol Buffers - Fastest overall serializer which also happens to produce the smallest output. Developed by Google. Using protobuf-net implementation.
  • Utf8Json - Definitely Fastest and Zero Allocation JSON Serializer for C#(.NET, .NET Core, Unity and Xamarin), this serializer write/read directly to UTF8 binary so boostup performance

How can I store an object into Redis?

There are several methods in ICacheClient that can solve this request.

var user = new User()
{
	Firstname = "Ugo",
	Lastname = "Lattanzi",
	Twitter = "@imperugo"
	Blog = "http://tostring.it"
}

bool added = myCacheClient.Add("my cache key", user, DateTimeOffset.Now.AddMinutes(10));

How can I retrieve an object into Redis?

Easy:

var cachedUser = myCacheClient.Get<User>("my cache key");

How can I retrieve multiple object with single roundtrip?

That's a cool feature that is implemented into ICacheClient implementation:

var cachedUsers = myCacheClient.GetAll<User>(new {"key1","key2","key3"});

How can I add multiple object with single roundtrip?

That's a cool feature that is implemented into ICacheClient implementation:

IList<Tuple<string, string>> values = new List<Tuple<string, string>>();

values.Add(new Tuple<string, string>("key1","value1"));
values.Add(new Tuple<string, string>("key2","value2"));
values.Add(new Tuple<string, string>("key3","value3"));

bool added = sut.AddAll(values);

Can I search keys into Redis?

Yes that's possible using a specific pattern. If you want to search all keys that start with myCacheKey:

var keys = myCacheClient.SearchKeys("myCacheKey*");

If you want to search all keys that contain with myCacheKey:

var keys = myCacheClient.SearchKeys("*myCacheKey*");

If you want to search all keys that end with myCacheKey:

var keys = myCacheClient.SearchKeys("*myCacheKey");

Can I use a Redis method directly from ICacheClient without add another dependency to my class?

Of course you can. ICacheClient exposes a readonly property named Database that is the implementation of IDatabase by StackExchange.Redis

myCacheClient.Database.SetAdd("mykey","another key");

How can I get server information?

ICacheClient has a method GetInfo and GetInfoAsync for that:

var info = myCacheClient.GetInfo();

For more info about the values returned, take a look here

Contributing

Getting started with Git and GitHub

Once you're familiar with Git and GitHub, clone the repository and start contributing.

stackexchange.redis.extensions's People

Contributors

aishelm avatar aliosman1981 avatar almazik avatar avgardyan avatar carlosboeing avatar cbigsby avatar d-franklin avatar doctorthatguy avatar eugenekrapivin avatar gldraphael avatar imperugo avatar jessepreiner avatar jkruer01 avatar jonathaneckman avatar lisberpontes avatar lucax88x avatar ppanyukov avatar rajasekarshanmugam avatar rjmurillo avatar rushfrisby avatar smariussorin avatar ziyasal avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.