Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example Analysis of java object as key value

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the example analysis of java object as a key value, the content is very detailed, interested friends can refer to, hope to be helpful to you.

1. Description of implementation method

The following is an extension of the handwritten redis @ Cacheable annotation that supports expiration time settings.

1.1 problem description

General usage of @ Cacheable (key = "'leader'+#p0 + # p1 + # p2"), where # p0 represents the first parameter of the method, # p1 represents the second parameter, and so on.

Currently, the first parameter of the method is the object of Java, but the original annotation only supports the basic data type of Java.

1.2 implementation steps

1. Add new parameters to the original comment

ObjectIndexArray indicates which corner parameters (starting with 0) are java objects, and objectFieldArray indicates the corresponding position. The field value of this object is used as key.

two。 How to get the object of the parameter and the value of the field

The reflection of the java used, and the splicing get method gets the value of the field.

two。 source code

Modify the java annotation @ ExtCacheable, and use @ NewCacheable in this article

Package com.huajie.annotation; import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target; @ Target ({ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) public @ interface NewCacheable {String key () default ""; int [] objectIndexArray (); String [] objectFieldArray (); int expireTime () default 1800

SpringAop section NewCacheableAspect

There is no change in the overall process of obtaining AOP

It is mainly the way of obtaining key values, which has changed.

Reflection technology using Java

The complete code is as follows:

Package com.huajie.aspect; import com.huajie.annotation.NewCacheable;import com.huajie.utils.RedisUtil;import com.huajie.utils.StringUtil;import lombok.extern.slf4j.Slf4j;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import java.lang.reflect.Method Import java.util.ArrayList;import java.util.List; / * redis cache processing is not suitable for internal method calls (this.) Or private * / @ Component@Aspect@Slf4jpublic class NewCacheableAspect {@ Autowired private RedisUtil redisUtil; @ Pointcut ("@ annotation (com.huajie.annotation.NewCacheable)") public void annotationPointcut () {} @ Around ("annotationPointcut ()") public Object doAround (ProceedingJoinPoint joinPoint) throws Throwable {/ / get the currently visited class Class className = joinPoint.getTarget (). GetClass () / / the name of the accessed method String methodName = joinPoint.getSignature () .getName (); / / the type of the method's parameters Class [] argClass = ((MethodSignature) joinPoint.getSignature ()) .getParameterTypes (); Object [] args = joinPoint.getArgs (); String key = ""; int expireTime = 3600 Try {/ / method objects accessed Method method = className.getMethod (methodName, argClass); method.setAccessible (true); / / determine whether @ ExtCacheable annotations exist if (method.isAnnotationPresent (NewCacheable.class)) {NewCacheable annotation = method.getAnnotation (NewCacheable.class); key = getRedisKey (args, annotation) ExpireTime = getExpireTime (annotation);}} catch (Exception e) {throw new RuntimeException ("redis cache comment parameter exception", e);} log.info (key); boolean hasKey = redisUtil.hasKey (key); if (hasKey) {return redisUtil.get (key) } else {Object res = joinPoint.proceed (); redisUtil.set (key, res); redisUtil.expire (key, expireTime); return res;}} private int getExpireTime (NewCacheable annotation) {return annotation.expireTime ();} private String getRedisKey (Object [] args, NewCacheable annotation) throws Exception {String primalKey = annotation.key () / / get # p0. Set List keyList = getKeyParsList (primalKey); for (String keyName: keyList) {int keyIndex = Integer.parseInt (keyName.toLowerCase (). Replace ("# p", "")); Object parValue = getParValue (annotation, keyIndex, args); primalKey = primalKey.replace (keyName, String.valueOf (parValue)) } return primalKey.replace ("+", "). Replace ("'",");} private Object getParValue (NewCacheable annotation, int keyIndex, Object [] args) throws Exception {int [] objectIndexArray = annotation.objectIndexArray (); String [] objectFieldArray = annotation.objectFieldArray (); if (existsObject (keyIndex, objectIndexArray)) {return getParValueByObject (args, keyIndex, objectFieldArray) } else {return args [keyIndex];}} private Object getParValueByObject (Object [] args, int keyIndex, String [] objectFieldArray) throws Exception {Class cls = args [keyIndex] .getClass (); Method method; if (objectFieldArray.length > = keyIndex) {method = cls.getMethod ("get" + StringUtil.firstCharToUpperCase (objectFieldArray [keyIndex])) } else {method = cls.getMethod ("get" + StringUtil.firstCharToUpperCase (cls.getFields () [0] .getName ();} method.setAccessible (true); log.info (method.getName ()); return method.invoke (args [keyIndex]) } private boolean existsObject (int keyIndex, int [] objectIndexArray) {if (objectIndexArray = = null | | objectIndexArray.length = 0) {int plusIndex = key.substring (key.indexOf ("#"). IndexOf ("+"); int indexNext = 0; String parName = ""; int indexPre = key.indexOf ("#") If (plusIndex > 0) {indexNext = key.indexOf ("#") + key.substring (key.indexOf ("#"). IndexOf ("+"); parName = key.substring (indexPre, indexNext);} else {parName = key.substring (indexPre);} ListPar.add (parName.trim ()) Key = key.substring (indexNext + 1); if (key.indexOf ("#") > = 0) {ListPar.addAll (getKeyParsList (key));}} return ListPar;} 3. test

How to use the business module controller

@ RequestMapping ("queryQuotaTreeData") @ ResponseBody public List getTreeData () {QuotaManage quotaManage = new QuotaManage (); quotaManage.setQuotaName ("Test 22222"); List list = this.quotaManageService.queryQuotaTreeData (quotaManage); return list;}

{0} in the implementation layer objectIndexArray represents the 0th parameter, and "quotaName" in objectFieldArray represents the field name in the corresponding object.

@ Override @ NewCacheable (key= "test+#p0", objectIndexArray = {0}, objectFieldArray = {"quotaName"}) public List queryQuotaTreeData (QuotaManage quotaManage) {List returnNodesList = new ArrayList (); List nodeList = this.mapper.queryQuotaTreeData (); returnNodesList = treeUtils.getParentList (nodeList); log.info (nodeList.size () + "); return returnNodesList }

The name of the get method and the acquired field value of the screenshot stitching in the console

Screenshot of Redis

On the java object as a key value of the example analysis is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report