Flexible implementation of microservice per request to improve IO efficiency (3), perio

Source: Internet
Author: User

Flexible implementation of microservice per request to improve IO efficiency (3), perio
Efficiency

Flexible implementation of microservice per request to improve IO efficiency (2) how to release the cache stored in ThreadLocal correctly, the most reason is to clear the cache after the method we requested is executed.

Filter

Because my project is based on dubbo, you can use the Filter mechanism provided by dubbo to accomplish this. You can see the status of the filter:

Final effect:

Create ThreadLocalCacheFilter

Create a class and let it implement the Filter interface. It is just a method called invoke. The function of this invoke method is similar to the method Around AOP. If we want to clear the cache, there will be some operations, only need to be in front of return, invoker. add the clearing logic after the invoke method. Because the cache is unique to the thread, you can simply clear it.

Due to the Filter loading mechanism problem, it is a problem to use Spring annotations in the Filter. Currently, cacheManager is loaded by manually obtaining beans, I will briefly mention the filter loading mechanism of dubbo later. If you have other good solutions, please let me know.

@Activatepublic class ThreadLocalCacheFilter implements Filter {    private Logger logger = LoggerFactory.getLogger(getClass().getName());    @Autowired    private CacheManager cacheManager;    private void clearCache(){        if(null==cacheManager){            ApplicationContext appCtx = ApplicationContextUtils.getApplicationContext();            cacheManager= appCtx.getBean(ThreadLocalCacheManager.class);        }        Collection<String> cacheNames= this.cacheManager.getCacheNames();        if(null!=cacheNames) {            for(String cacheName :cacheNames) {                this.cacheManager.getCache(cacheName).clear();            }        }    }    @Override    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {        Result result=invoker.invoke(invocation);        this.logger.info("release cache start");        this.clearCache();        this.logger.info("release cache end");        return result;    }}

@ Active Annotation
To activate the filter, We need to load the @ Active Annotation on the created custom filter class, check its related parameters, or do not configure

  • Group, one of the conditions, specifying the server or consumer
  • Value, one of the conditions, is generally the English name of the filter, used in the dubbo configuration file
  • Before: sorting information, such as the filter
  • After, sorting information, such as the filter
  • Order, sorting information, which should be at the top of the list with smaller values
Load Filter

The extended filter compiled by dubbo must be loaded before it can be used. dubbo loads the filter from the three directories under the resource.

  • META-INF/services/
  • META-INF/dubbo/
  • META-INF/dubbo/internal/

Create a pure file com. alibaba. dubbo. rpc. Filter and put it in the corresponding directory. Then write the filter information to be used.

threadLocalCacheFilter=com.filter.ThreadLocalCacheFilter
Apply Filter

Add the following content to the dubbo configuration file:

<dubbo:provider filter="threadLocalCacheFilter" />
Dubbo Filter

Dubbo has a class ProtocolFilterWrapper that loads all the filters in the project and performs chained calls.

If you want to learn the design model, you can see how this class uses the responsibility chain model.
Here, we only need to look at one method:

  • ExtensionLoader loads and implements the Filter interface class.
  • Filter Filters Based on filtering conditions, which have sorting
  • Call all filters that meet the criteria and are sorted cyclically

Note that the variable next is passed to next when the current method executes the invoke method. There should be the last terminator to process the actual method execution.

 private static <T> Invoker<T> buildInvokerChain(final Invoker<T> invoker, String key, String group) {        Invoker<T> last = invoker;        List<Filter> filters = ExtensionLoader.getExtensionLoader(Filter.class).getActivateExtension(invoker.getUrl(), key, group);        if (filters.size() > 0) {            for (int i = filters.size() - 1; i >= 0; i --) {                final Filter filter = filters.get(i);                final Invoker<T> next = last;                last = new Invoker<T>() {                    public Class<T> getInterface() {                        return invoker.getInterface();                    }                    public URL getUrl() {                        return invoker.getUrl();                    }                    public boolean isAvailable() {                        return invoker.isAvailable();                    }                    public Result invoke(Invocation invocation) throws RpcException {                        return filter.invoke(next, invocation);                    }                    public void destroy() {                        invoker.destroy();                    }                    @Override                    public String toString() {                        return invoker.toString();                    }                };            }        }        return last;    }
Summary

After completing three notes, from the initial Context problem to the release of the cache, you can easily use the request-level cache. It is worth noting that it is necessary to clarify which schemes are suitable for request-level caching. For example, to query a user, insert a user in some operations before querying the user. If the query is a method marked with a request-level cache, the problem may occur.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.