Skip to content

Commit

Permalink
Tutorial RedisSortedSets
Browse files Browse the repository at this point in the history
  • Loading branch information
taswar committed Dec 29, 2016
1 parent 65f74c0 commit 6383b68
Show file tree
Hide file tree
Showing 8 changed files with 357 additions and 0 deletions.
4 changes: 4 additions & 0 deletions 7.RedisSortedSets/README
@@ -0,0 +1,4 @@
Source Code for Blog Post on Redis for .NET Developers
- Describes Set datatype in Redis with C# using a console app.
- To read the content please visit
http://taswar.zeytinsoft.com/2016/12/29/redis-sorted-sets-datatype/
22 changes: 22 additions & 0 deletions 7.RedisSortedSets/RedisSortedSets.sln
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RedisSortedSets", "RedisSortedSets\RedisSortedSets.csproj", "{5CE3A981-5449-4B8A-9B60-65CFA987084A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5CE3A981-5449-4B8A-9B60-65CFA987084A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5CE3A981-5449-4B8A-9B60-65CFA987084A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5CE3A981-5449-4B8A-9B60-65CFA987084A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5CE3A981-5449-4B8A-9B60-65CFA987084A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
9 changes: 9 additions & 0 deletions 7.RedisSortedSets/RedisSortedSets/App.config
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="redis.connection" value="localhost:32769"/>
</appSettings>
</configuration>
189 changes: 189 additions & 0 deletions 7.RedisSortedSets/RedisSortedSets/Program.cs
@@ -0,0 +1,189 @@
using StackExchange.Redis;
using System;

namespace RedisSortedSets
{
class Program
{
static void Main(string[] args)
{
var redis = RedisStore.RedisCache;

RedisKey topHackerKeys = "hackers";
RedisKey alphaKey = "alphaKey";
RedisKey destinationKey = "destKey";
RedisKey intersectKey = "intersectKey";


redis.KeyDelete(topHackerKeys, CommandFlags.FireAndForget);
redis.KeyDelete(alphaKey, CommandFlags.FireAndForget);
redis.KeyDelete(intersectKey, CommandFlags.FireAndForget);
redis.KeyDelete(destinationKey, CommandFlags.FireAndForget);

//According to http://www.arkhitech.com/12-greatest-programmers-of-all-time/
var topProgrammers = new[] {
"Dennis Ritchie",
"Linus Torvalds",
"Bjarne Stroustrup",
"Tim Berners-Lee",
"Brian Kernighan",
"Donald Knuth",
"Ken Thompson",
"Guido van Rossum",
"James Gosling",
"Bill Gates",
"Niklaus Wirth",
"Ada Lovelace"
};

//add 12 items to the sorted set
for (int i = 0, j = 1; i < topProgrammers.Length; i++, j++)
redis.SortedSetAdd(topHackerKeys, topProgrammers[i], j);

var members = redis.SortedSetScan(topHackerKeys);

Console.WriteLine(string.Join(",\n", members));
/* output
* Dennis Ritchie: 1,
* Linus Torvalds: 2,
* Bjarne Stroustrup: 3,
* Tim Berners-Lee: 4,
* Brian Kernighan: 5,
* Donald Knuth: 6,
* Ken Thompson: 7,
* Guido van Rossum: 8,
* James Gosling: 9,
* Bill Gates: 10,
* Niklaus Wirth: 11,
* Ada Lovelace: 12
*/


Console.WriteLine(redis.SortedSetLength(topHackerKeys)); //output 12

var byRanks = redis.SortedSetRangeByRank(topHackerKeys);
Console.WriteLine(string.Join(",\n", byRanks));
/* output
* Dennis Ritchie,
* Linus Torvalds,
* Bjarne Stroustrup,
* Tim Berners-Lee,
* Brian Kernighan,
* Donald Knuth,
* Ken Thompson,
* Guido van Rossum,
* James Gosling,
* Bill Gates,
* Niklaus Wirth,
* Ada Lovelace
*/


Console.WriteLine(redis.SortedSetRank(topHackerKeys, "Linus Torvalds")); //output 1


var byScore = redis.SortedSetRangeByScore(topHackerKeys, 1, topProgrammers.Length,Exclude.None, Order.Descending);
Console.WriteLine(string.Join(",\n", byScore));
/*output
* Ada Lovelace,
* Niklaus Wirth,
* Bill Gates,
* James Gosling,
* Guido van Rossum,
* Ken Thompson,
* Donald Knuth,
* Brian Kernighan,
* Tim Berners-Lee,
* Bjarne Stroustrup,
* Linus Torvalds,
* Dennis Ritchie
*/

redis.SortedSetIncrement(topHackerKeys, "Linus Torvalds", 100);

Console.WriteLine(redis.SortedSetScore(topHackerKeys, "Linus Torvalds")); //output 102, since it was 2 to being with

redis.SortedSetDecrement(topHackerKeys, "Linus Torvalds", 100);

Console.WriteLine(redis.SortedSetScore(topHackerKeys, "Linus Torvalds")); //output 2 back to original value

redis.SortedSetAdd(alphaKey, "a", 1);
redis.SortedSetAdd(alphaKey, "b", 1);
redis.SortedSetAdd(alphaKey, "c", 1);

redis.SortedSetCombineAndStore(SetOperation.Union, destinationKey, topHackerKeys, alphaKey);

members = redis.SortedSetScan(destinationKey);
Console.WriteLine("**********UNION**************");
Console.WriteLine(string.Join(",\n", members));
/* output
* Dennis Ritchie: 1,
* a: 1,
* b: 1,
* c: 1,
* Linus Torvalds: 2,
* Bjarne Stroustrup: 3,
* Tim Berners-Lee: 4,
* Brian Kernighan: 5,
* Donald Knuth: 6,
* Ken Thompson: 7,
* Guido van Rossum: 8,
* James Gosling: 9,
* Bill Gates: 10,
* Niklaus Wirth: 11,
* Ada Lovelace: 12
*/

redis.SortedSetCombineAndStore(SetOperation.Intersect, intersectKey, topHackerKeys, destinationKey);
members = redis.SortedSetScan(intersectKey);

//note it double the key scores
Console.WriteLine("**********INTERSECT**************");
Console.WriteLine(string.Join(",\n", members));
/*output
* Dennis Ritchie: 2,
* Linus Torvalds: 4,
* Bjarne Stroustrup: 6,
* Tim Berners-Lee: 8,
* Brian Kernighan: 10,
* Donald Knuth: 12,
* Ken Thompson: 14,
* Guido van Rossum: 16,
* James Gosling: 18,
* Bill Gates: 20,
* Niklaus Wirth: 22,
* Ada Lovelace: 24
*/

members = redis.SortedSetRangeByScoreWithScores(topHackerKeys, 2, 4);
Console.WriteLine("**********RANGE BY SCORE WITH SCORES**************");
Console.WriteLine(string.Join(",\n", members));
/*output
* Linus Torvalds: 2,
* Bjarne Stroustrup: 3,
* Tim Berners-Lee: 4
*/


redis.SortedSetRemove(alphaKey, "a");
members = redis.SortedSetScan(alphaKey);
Console.WriteLine("**********REMOVE**************");
Console.WriteLine(string.Join(",\n", members));
/*output
* b: 1,
* c: 1
*/

redis.SortedSetRemoveRangeByScore(destinationKey, 0, 11);
members = redis.SortedSetScan(destinationKey);
Console.WriteLine("**********REMOVE BY SCORE**************");
Console.WriteLine(string.Join(",\n", members));
/* output
* Ada Lovelace: 12
*/


Console.ReadKey();
}
}
}
36 changes: 36 additions & 0 deletions 7.RedisSortedSets/RedisSortedSets/Properties/AssemblyInfo.cs
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RedisSortedSets")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RedisSortedSets")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5ce3a981-5449-4b8a-9b60-65cfa987084a")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
68 changes: 68 additions & 0 deletions 7.RedisSortedSets/RedisSortedSets/RedisSortedSets.csproj
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{5CE3A981-5449-4B8A-9B60-65CFA987084A}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>RedisSortedSets</RootNamespace>
<AssemblyName>RedisSortedSets</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="StackExchange.Redis, Version=1.1.608.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\StackExchange.Redis.1.1.608\lib\net46\StackExchange.Redis.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RedisStore.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
25 changes: 25 additions & 0 deletions 7.RedisSortedSets/RedisSortedSets/RedisStore.cs
@@ -0,0 +1,25 @@
using StackExchange.Redis;
using System;
using System.Configuration;

namespace RedisSortedSets
{
public class RedisStore
{
private static readonly Lazy<ConnectionMultiplexer> LazyConnection;

static RedisStore()
{
var configurationOptions = new ConfigurationOptions
{
EndPoints = { ConfigurationManager.AppSettings["redis.connection"] }
};

LazyConnection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(configurationOptions));
}

public static ConnectionMultiplexer Connection => LazyConnection.Value;

public static IDatabase RedisCache => Connection.GetDatabase();
}
}
4 changes: 4 additions & 0 deletions 7.RedisSortedSets/RedisSortedSets/packages.config
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="StackExchange.Redis" version="1.1.608" targetFramework="net461" />
</packages>

0 comments on commit 6383b68

Please sign in to comment.