Flexible implementation of microservice per request to improve IO efficiency, perio
Efficiency
During the same business operation, some operations are often executed repeatedly. Logically, it is ideal to only execute one operation. The operations mentioned here refer to some IO operations, such as obtaining information about the logon user from the database. That is to say, if a request contains five small logics, these five logics contain three operations to obtain user information. Ideally, only one operation is loaded from the database, and the other two operations are obtained from the cache.
- Each service is called multiple times to request user information independently.
- One call and multiple reads. First load from the Context, if the load fails from the database, and finally save the result to the Context.
Prerequisites
This is a microservice implemented by dubbo in a non-web environment. If it is a web environment, it is easy to solve the problem, because we can make full use of the three bean lifecycle Special mentioned in Spring Framwork to solve the problem:
Case
To migrate old price data to new price data, the steps are as follows:
- Delete the relationship between old and new prices because repeated migration is required.
- Disable an existing price rule that describes the logic that the price takes effect in a certain scenario.
- Create a new price
- Create a new rule
- Enable new rules
The price, rules, and relationship data in the above steps belong to three business objects respectively. They all have CRUD service interfaces. These CRUD must record operator information, the record standard is the token held by the operator passed in by the interface. We need to convert the token into information such as userId, userName, and price, rules, and so on, and store it together.
The sequence diagram is as follows:
Problem: the efficiency of migrating a single item to read user information multiple times is low
Because the migration price involves operations on multiple objects, the interfaces for operating these specific business objects do not support passing specific userids, and userName only supports token, therefore, it is inevitable that the operator information will be queried Based on the token when saving the price and other information. During a price test, data migration involves obtaining user information more than 20 times, which is inefficient. How can this problem be solved?
Status quo
Since the microservice I currently implement is stateless and not a web environment, the scope functions of the bean mentioned above cannot be used.
Target
Implement a function similar to the request scope. A single request is executed only once, and other requests obtain results from the cache to improve the efficiency of IO operations.
Solution
TreadLocal can be used as a cache to store frequently read data. Added CacheContext to obtain the user from CacheContext first. If it is null, it is loaded from the database and written back to Treadlocal, the next request for user information can hit the cache and does not need to be loaded from the database again, which obviously improves the efficiency.
The sequence diagram is as follows:
The implementation steps are as follows:
- Create Context Data Object
The cached container is TreadLocal. You can define multiple attributes to be cached and provide a method to clear all the caches. The cleanup method is required. Otherwise, it will stay in the thread and get the data stored in the previous request when the thread is reused.
@ Servicepublic class ProductContext {private static Logger logger = Logger. getLogger (CiaServiceImpl. class); private ThreadLocal <CiaUserInfo> ciaUserInfoThreadLocal = new ThreadLocal <> (); private void clearCiaUserInfo () {this. ciaUserInfoThreadLocal. remove (); this.logger.info ("getTokenInfo cache cleared");} public void setCiaUserInfoToCache (CiaUserInfo ciaUserInfo) {this. clearCiaUserInfo (); this. ciaUserInfoT HreadLocal. set (ciaUserInfo); this.logger.info ("store getTokenInfo in cache");} public CiaUserInfo getCiaUserInfoFromCache (String token) {CiaUserInfo ciaUserInfo = this. ciaUserInfoThreadLocal. get (); if (null! = CiaUserInfo) {this.logger.info ("Get user information from cache getTokenInfo");} return ciaUserInfo;} public void clearAll () {this. clearCiaUserInfo (); this.logger.info ("The ProductContext cache is cleared successfully ");}}
- Modify the service class used to obtain user information and use Context to perform cache operations.
public CiaUserInfo getTokenInfo(String token) throws Exception { CiaUserInfo result = this.productContext.getCiaUserInfoFromCache(token); if(null!=result){ return result; } else { result=new CiaUserInfo(); } //...get user from db this.productContext.setCiaUserInfoToCache(result); return result; }
- Add annotations to identify which methods require caching
@ Target ({ElementType. TYPE, ElementType. METHOD}) @ Retention (RetentionPolicy. RUNTIME) public @ interface LocalCacheContext {/*** whether to start * @ return */boolean enable () default true ;}
- Add interceptor
The information stored in TreadLocal needs to be released in a timely and effective manner, with the annotations stated above.
@Aspectpublic class LocalCacheContextInterceptor { private Logger logger = LoggerFactory.getLogger(getClass().getName()); @Autowired private ProductContext productContext; @Pointcut("execution(* product.service.service.impl.*.*(..))") public void pointCut() { } @After("pointCut()") public void after(JoinPoint joinPoint) throws ProductServiceException { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method targetMethod = methodSignature.getMethod(); LocalCacheContext localCacheContext= targetMethod.getAnnotation(LocalCacheContext.class); if(null!=localCacheContext){ this.productContext.clearAll(); } }}
@LocalCacheContext public void migrationPrice(Long priceId) throws ProductServiceException { this.migrationPriceService.migrationPrice(priceId); }