Skip to content

Azure Cache for Redis

  • Stores frequently accessed data on RAM (instead of disk) for a faster access
  • Azure Redis is a serverless service
  • Data types of redis
  • Strings
  • Lists
  • Sets
  • Hashes
  • ...
  • Prices
  • C6 Basic: 53 GB, R$3000/month
  • C6 Standard: 53 GB, Replication, R$7000/month
  • P5 Premium: 120 GB, Replication, R$36000/month
  • E100 Premium: 100 GB, Replication, R$45000/month
  • Use the Console to set key-value pairs
SET "key" "value"

Nuget Library

  • StackExchange.Redis
<ItemGroup>
  <PackageReference Include="StackExchange.Redis" Version="2.2.4" />
</ItemGroup>
  • Set and Get keys to Redis (simple)
class Program
{
  private static Lazy<ConnectionMultiplexer> cache_connection = CreateConnection();

  public static ConnectionMultiplexer Connection
  {
    get
    {
      return cache_connection.Value; // Get the Redis connection
    }
  }

  private static Lazy<ConnectionMultiplexer> CreateConnection()
  {
    string cache_connectionstring = "hvitoi.redis.cache.windows.net:6380,password=redis-password,ssl=True,abortConnect=False";
    return new Lazy<ConnectionMultiplexer>(() =>
    {
      return ConnectionMultiplexer.Connect(cache_connectionstring);
    });
  }

  static void Main(string[] args)
  {
    IDatabase cache = Connection.GetDatabase();

    // Set key-value pair (simple string)
    cache.StringSet("Course Name", "AZ-204 - Developing Azure solutions");
    cache.KeyExpire("Course Name", new TimeSpan(0, 0, 30));

    if (cache.KeyExists("Course Name"))
      Console.WriteLine(cache.StringGet("Course Name"));
    else
      Console.WriteLine("Key does not exist");

    // Set key-value pair (dotnet class)
    Order _order =
    new Order() { OrderID = "O1", Quantity = 10, UnitPrice = 9.99m };

    cache.StringSet(_order.OrderID, JsonSerializer.Serialize<Order>(_order));
    Order get_order = JsonSerializer.Deserialize<Order>(cache.StringGet(_order.OrderID));
  }
}
  • Set and Get keys to Redis (integration with SQL databases)
public class CourseService
{
  private static Lazy<ConnectionMultiplexer> cache_connection = CreateConnection();

  public static ConnectionMultiplexer Connection
  {
    get
    {
      return cache_connection.Value;
    }
  }

  private static Lazy<ConnectionMultiplexer> CreateConnection()
  {
    string cache_connectionstring = "hvitoi.redis.cache.windows.net:6380,password=redis-password,ssl=True,abortConnect=False";
    return new Lazy<ConnectionMultiplexer>(() =>
    {
      return ConnectionMultiplexer.Connect(cache_connectionstring);
    });
  }

  private SqlConnection GetConnection(string _connection_string)
  {
    return new SqlConnection(_connection_string);
  }

  public IEnumerable<Course> GetCourses(string _connection_string)
  {
    List<Course> _lst = new List<Course>();

    IDatabase cache = Connection.GetDatabase();

    // If data exists in cache
    if (cache.KeyExists("Course"))
    {
      _lst = JsonSerializer.Deserialize<List<Course>>(cache.StringGet("Course"));
      return _lst;
    }
    // If data does not exist in cache
    else
    {
      // Open sql connection
      SqlConnection _connection = GetConnection(_connection_string);
      _connection.Open();

      // Retrieve data from SQL
      string _statement = "SELECT CourseID,CourseName,rating from Course";
      SqlCommand _sqlcommand = new SqlCommand(_statement, _connection);
      using (SqlDataReader _reader = _sqlcommand.ExecuteReader())
      {
        while (_reader.Read())
        {
          Course _course = new Course()
          {
            CourseID = _reader.GetInt32(0),
            CourseName = _reader.GetString(1),
            Rating = _reader.GetDecimal(2)
          };
          _lst.Add(_course);
        }
        cache.StringSet("Course", JsonSerializer.Serialize<List<Course>>(_lst)); // Save data to redis, so that next time it fetches from cache
      }
      _connection.Close();
    }
    return _lst;
  }

  public void UpdateCourse(Course p_course, string _connection_string)
  {
    // Open SQL connection
    SqlConnection _connection = GetConnection(_connection_string);
    _connection.Open();

    // Statement
    StringBuilder _statement = new StringBuilder("UPDATE Course SET Rating=");
    _statement.Append(p_course.Rating);
    _statement.Append(" WHERE CourseID=");
    _statement.Append(p_course.CourseID);

    SqlCommand _sqlcommand = new SqlCommand(_statement.ToString(), _connection);
    _sqlcommand.ExecuteNonQuery();
  }

  public Course GetCourse(string id, string _connection_string)
  {
    IEnumerable<Course> _courses = this.GetCourses(_connection_string);
    Course _course = _courses.FirstOrDefault(m => m.CourseID == Int32.Parse(id));
    return _course;
  }
}