다음을 통해 공유


Access Azure Redis Cache with an API App

https://msdnshared.blob.core.windows.net/media/2016/05/0640_NinjaAwardTinyGold.pngGold Award Winner


Introduction

Microsoft Azure Cache (Redis) is based on open source Redis Cache. And Microsoft created a Platform as a Service (PaaS) around it, which can be provisioned through the Microsoft Azure Portal or PowerShell scripts. The service will give you a secure, and dedicated Redis cache hosted in a Microsoft data center. Data can be stored as key/value pair and access via an API or other means. This article will show how to access data in Redis Cache from an Azure API App.

Scenario

An Azure API App will access data in the Redis Cache. The data will be query by one of the operations of the WebAPI and update data in another operation call. The API App will have two operations one query data (GET) by a parameter and update existing data (POST). The diagram below demonstrates the scenario.

Set up

A Redis Cache will be provisioned and sample data will loaded into the cache. An API App will be built in Visual Studio and be deployed in an API App in Microsoft Azure. The API App will have swagger support, hence we can test the API in a browser locally and once the API App is deployed. Provisioning the Redis Cache is described in the online documentation, see the section create your first Redis.

Prerequisites

To build a solution similar to this one or create API’s yourself that you like to host in Azure than you need an Azure Account and subscription. If you do have access to a subscription than you should be able to connect to it via Visual Studio in the Server Explorer as shown in the picture below.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Connect%20to%20Azure%20VS_zps3ohvwmy1.png

You will need to install the latest Azure SDK for Visual Studio 2013.

Walkthrough

The Getting Started with ASP.NET Web API 2 is an excellent resource to get you up to speed building a Web API. In a similar fashion the Web API to access Redis Cache data has been built using the ASP.NET Template in Visual Studio 2013.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/WebAPI%201%20VS2013_zps6jdnzcol.png

Notice the Application Insight is not added to the project. You choose to do so if you need to understand and optimize application performance. To keep the focus in this article on communication with Redis we not going to leverage the functionality. More on Application Insight see Visual Studio Application Insight. Once OK has been click the following dialog will appear.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/WebAPI%206%20VS2013_zps21ibhbf5.png

In this dialog we choose Azure API App, as this provide an out of box implementation of swagger (reference to Swashbuckle.Core is included). This saves us time as with Web API template you need to add Swashbuckle yourself and instrument the code. The other reason is we just need the references for the Web API and nothing else. Click OK to proceed and another dialog screen will appear asking us for details for the hosting environment. In the previous screen you can see we choose to Host the API in the cloud in an App Service. Now we need to specify the API App Name, Subscription, Resource Group and Price Plan. The latter can created manually or you can choose an existing one.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/WebAPI%203%20VS2013_zpslngppyl9.png

The Create will provision a publishing profile in your Visual Studio project.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Publishing%20Profile_zpsecysw0ct.png

We will navigate to the App_Start folder and open SwaggerConfig and uncomment the following piece:

    })
.EnableSwaggerUi(c =>
    {

By doing so we now have enabled the swagger UI.

Now we have a base we can start working with, which means we need to add a controller and a model (data) to work with. The model will be a representation of the data that will be obtained from the Redis Cache. It will represent an order with the following format:

{
  "id": "A345",
  "descr": "Microsoft Surface PRO 4 256Gb",
  "number": "12374623874568273648123",
  "amount": "1",
  "date": "15-2-2016"
}

The key is id and value is the complete JSON as represented above. A class will be added to the Models folder and have the following code.

namespace AzureRedisCacheAPI.Models
{
public class  Order
    {
        public string  id { get; set; }
        public string  descr { get; set; }
        public string  number { get; set; }
        public string  amount { get; set; }
        public string  date { get; set; }
    }
}

Next we will add a controller to Controllers folder. When choosing Add à Controller a dialog box will appear as shown in the picture below.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Controller%202_zps5a37azuq.png

Once the Controller class is created we will add a NuGet package to enable us to communicate with the Redis Cache. In Manage NuGet packages we will look for StackExchange.Redis and install it.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Redis%20Cache%20Nuget%201_zpskliwgmbq.png

Once the package is installed we will implement the code below into our controller class.

using System;
using System.Web.Http;
using System.Configuration;
using StackExchange.Redis;
using System.Web.Script.Serialization;
 
namespace AzureRedisCacheAPI.Controllers
{
    using Models;
 
    public class  OrderController : ApiController
    {
        private static  Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            return ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisConnectionString"]);
        });
 
        public static  ConnectionMultiplexer Connection
        {
            get
            {
                return lazyConnection.Value;
            }
        }
 
        [HttpGet]
        public Order Get(string id)
        {
            IDatabase cache = Connection.GetDatabase();
 
            string json = cache.StringGet(id);
 
            JavaScriptSerializer j = new  JavaScriptSerializer();
            Order order = (Order)j.Deserialize(json, typeof(Order));
 
            return order;
        }
 
        [HttpPost]
        public Order Change(string id,Order order)
        {
            IDatabase cache = Connection.GetDatabase();
 
            JavaScriptSerializer j = new  JavaScriptSerializer();
            string json = j.Serialize(order);
 
            try
            {
                cache.StringSet(order.id, json);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
 
            return order;
        }
    }
}

The implementation of the connection to Redis is derived from the How to Use Azure Redis Cache documentation from Microsoft Azure. The Get and Change methods support HTTP GET and POST. The GET will retrieve an order from the Redis with key id and the POST will change using the id. The change will be in the JSON payload.

Testing the solution locally in a browser

Once the project is build it can be started locally in a web browser i.e. one that you specify. In project properties we have specified to use local IIS express using the path (localhost) and random port.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Browser%20select_zps0gqdojby.png

A browser page will appear with HTTP 403 message.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/403_zpsogxce1hf.png

Add /swagger and you will see the swagger UI appear, which will show the operation. We will drill down and examine the operation documentation.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/swagger%20ui%20local_zpsojund8tx.png

We will fill in an id and click Try it out! We will see a response of the GET /api/Order{id}, where the ID is A345.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Test%20API%203_zps78vo6bjd.png

We can also test the change i.e. POST. By choosing the same id, A345, and past the payload from the GET into order and change the amount to 4 and click Try it out!

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Test%20API%202_zps3pi7hhuh.png

The result will be return in the response with the representation of how the order is stored in the Redis.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Test%20API%203_zps78vo6bjd.png

Deployment

Now we now the API functions as expected and we can deploy the API to Azure. We close the browser and stop debug of the API. Next we right click the Visual Studio project and choose Publish. A dialog will appear as shown below.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Deploy%201_zpsfabwfnv0.png

The settings in this screen are from the publishing settings and we can validate if the connection is valid by clicking Validate Connection.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Deploy10_zpshqrrzmiu.png

We have a valid connection, subsequently we click Next.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Deploy%202_zpsjbl1wepw.png

In the above dialog we can change the configuration setting if we want, specify any File Publish Options, which is not required here or specify any database (not present in the project). And finally we can click Next to preview the deployment. Click Preview and examine the output.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Deploy%203_zpsclwmcpb5.png

We see all the resources are in the deployment, hence we click Publish. And in the output Windows of Visual Studio we see the following in the screenshot below.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Deploy%204_zpsm21nuslk.png

Once the deployment is finished a browser window will appear.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Deploy%205_zpssts3mcoj.png

We add /swagger to it and have the Swagger UI available again.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Deploy%206_zpsgq6jytrn.png

Now we can repeat the same test as we did locally.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Deploy%207_zps9vlhmgo4.png

In the Microsoft Azure Portal we can find out API and look at some of the details.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Deploy%208_zpslnutmmav.png

And through All settings we can examine the API.

http://i208.photobucket.com/albums/bb152/Steef-Jan/Azure%20Redis%20Cache/Deploy%209_zps13plrlwf.png

Resources

This article scratched the surface around Redis Cache. We implemented a solution having a Web API as a wrapper around the Redis Cache. The following resources will provide more information.

Other aspects around API Apps have not been discussed, yet are equally important such as security, scalability, managing and monitoring. You can look into these aspects online in the API Apps Overview and related links.

See Also

Another important place to find an extensive amount of Microsoft Azure App Service related articles is the TechNet Wiki itself. The best entry point is Microsoft Azure App Service Resources on the TechNet Wiki.