preface

There are still a few things we haven’t demonstrated about sharing with Ocelot, so let’s talk about it. This time focus on the use of cache gateway Ocelot, integration with Polly for service governance, integration with IdentityServer4 for authentication and authorization to elaborate; If you’re interested in the last one, click here.

The body of the

1. Use caching

Ocelot cache is used to cache the downstream request results. If multiple requests are made to the downstream API, the request results can be obtained from the cache within the validity period to improve service performance.

The following demo code continues the previous code example, the code address is: github.com/zyq025/IDS4…

1.1 Use the default memory cache

In fact, you can use the cache by adding the following red box configuration:

Configuration description:

  • TtlSeconds: specifies the validity period of the configuration, in seconds.
  • Region: Region name, that is, partition cache data. Oeclot can provide a cache management interface, and then specify the area to clear the cache; In fact, Ocelot’s interface management cache is added;

With the configuration file ready, add a new test interface to ServiceAPI1 as follows:

Run the gateway and ServiceAPI1 projects and access the new interface based on the configured routing rules:

If you’re here and you’re wondering, you didn’t do any caching, just a simple configuration? Yes, Ocelot has a memory cache by default. Older versions of InMemoryCache use dictionaries to store key-value pairs. The new version of AspMemoryCache is implemented with IMemoryCache; So as long as the configuration is turned on, it can be used, but the function is relatively simple, but can be integrated with other extended caches, of course, can also be customized.

1.2 Integrating the CacheManager Cache

In addition to cache management, CacheManager encapsulates many functions, such as events, performance counters, and concurrent updates, making caching easier for developers to handle and configure. Here mainly demonstrates how to use, integrated into the Ocelot is not in detail description, explanation, please refer to website: cachemanager.michaco.net/documentati…

There are three simple steps to integrate CacheManager into Ocelot:

  • Introducing the Ocelot. Cache. CacheManager package;

  • Register the corresponding service;

  • To add a configuration file, you simply configure FileCacheOptions, which was used in the previous section.

    This completes the integration, runs the gateway and the service interface, and then accesses, again every ten seconds to retrieve the value; Isn’t memory based usage easy? What about distributed access? Can you store it in Redis or any other way? Yes

1.3 Integrating the CacheManager with Redis for distributed caching

First of all, you have to install a good Redis environment, which I will not expand, if you are interested in Redis series, there are special articles to share, enter Redis series.

  • Import the corresponding package and add Redis related configuration as follows:

  • Run the gateway and service interface, access, again every 10 seconds to get the new value, but this time the data is stored in Redis, the result is as follows:

1.4 Custom Cache

A custom cache can be created by inheriting the IOcelotCache interface and registering it with the container.

  • A custom cache class inherits the IOcelotCache interface.

  • Register the cache class with the container;

  • To see the result, use the FileCacheOptions information from the previous configuration file:

If there is no need for special customization, it is good to use ready-made wheels.

2. Integrate Polly for service governance

With WebAPI, interface timeouts, access exceptions, and high concurrency are common, and troubleshooting and resiliency prevention are inevitable. Polly is a very smooth integration with WebAPI. Go to Polly- Fault Handling and Resilience for more details.

Ocelot integrates with Polly super power, importing packages, registering services, and the rest of the functionality is easily implemented through configuration files

  • Import packages and register services

  • Time-out fuse configuration implementation

    To facilitate testing, add a TimeoutTest interface to ServiceAPI1 as follows:

    Then configure timeout fuses and then run through the gateway to access the interface:

    Through the above demonstration, if the timeout, do not keep the request waiting, timely feedback information; Ocelot’s default timeout is 90s. At the same time, it is also equipped with a circuit breaker mechanism, if there are three abnormal times, the circuit breaker will be three seconds.

  • The traffic limiting configuration is implemented, as demonstrated by the CacheTest interface in ServiceAPI1

    When the maximum number of requests is reached, you can customize the returned message and status code. You only need to add the following configuration to the global configuration:

    The running effect is as follows:

3. Integrate IdentityServer4 for authentication and authorization

Authentication and authorization is indispensable in API projects, but for micro-service projects, each service does authentication once, which is redundant, and the later code maintenance is not good, so it is a good solution to find a public entrance for unified authentication, and the integration of authentication and authorization functions on the gateway fully meets the requirements.

Ocelot integrates with IdentityServer4. Ocelot integrates with IdentityServer4. Ocelot integrates with Ocelot IdentityServer4. The steps are as follows:

  • Prepare a project for Identity server 4

    The github source code for the AuthorizationServerDemo project is: Github.com/zyq025/IDS4…

  • – Added authentication logic to Project Ocelot

  • Modifying a Configuration File

    Configure authentication information for routing is configured, including AuthenticationProviderKey corresponding values and registration services defined in the gateway project AuthenticationProviderKey values are consistent. If the authentication information is configured, the authentication is verified by the authorization server. Otherwise, no authentication is performed.

  • The running results are as follows:

    As shown in the figure above, the corresponding API is protected. Try getting a Token and using it to access the API address that requires authentication, and see if you can ask; For the sake of demonstration, we will use the Postman tool, as follows:

    The Token has been obtained above. If you are in doubt, you can refer to the previous IDS4 article. Put the Token in the request header to access the API address to be authenticated as follows:

    Finally, normal access to the interface, unified in the gateway to do common logic, to avoid the function of each service to achieve redundancy, in the late maintenance and replacement is also very convenient.

Source code address: github.com/zyq025/IDS4…

conclusion

So far, Ocelot’s common functions have been demonstrated. These examples only provide ideas for specific applications. You need to pay attention to them according to your needs.

In the next step, we will continue to talk about the development applications such as call between services and distributed final consistency. We will also integrate some middleware for log monitoring and analysis as well as link tracking. For deployment, we will also share Nignx, Docker and K8s series.

A handsome guy who was made ugly by the program, pay attention to “Code variety circle “, learn with me ~~~