JAVA development (use of Redis @Cacheable annotation)

The @Cacheable annotation is used for query operations, first look up from the cache, if the cache does not exist, go to the database to check, and then write the query results to the cache.

@EnableCaching is required on the startup class

@EnableCaching
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application .class,args);
	}
}

The @Cacheable annotation is on the method, indicating that the return result of the method can be cached. That is to say, the return result of this method will be placed in the cache, so that when the method is called with the same parameters in the future, the value in the cache will be returned without actually executing the method.

    @GetMapping("gettoken")
    @Cacheable(value = "member#PT1H", key = "'qywxmodel:token:'+ #corpid", condition = "#language = 1")
    Map<String, Object> gettoken(@RequestParam("corpid")String corpid, @RequestParam("corpsecret")String corpsecret);
   

@Cacheable annotates three properties.
value : required. It is a name chosen by myself, through which it indicates where the bookList returned when this method is called for the first time will be stored in memory.
key : optional. To use the SpEL expression, this corresponds to the parameter username. When the value of the incoming username changes, the data in the cache will not be retrieved, but the getBooksByUsernameAndLanguage method will be executed. (This is necessary, because the username changes, the return value also changes, and the data in the cache does not match, so this option is very important). Spring uses the signature of the method as the key by default.
condition: Do you want to cache the result bookList returned by the method? condition adds a qualification. In this example, the returned bookList will be cached only if the incoming language code is 1. If other values ​​are passed to language, then the bookList will not be cached.

So how do you need to update the cache? This requires @CachePut

The logic of @Cacheable is: look up the cache - return if there is one - execute the method body if not - cache the result; the logic of
@CachePut is: execute the method body - cache the result;
so @Cacheable is suitable for the method of querying data, @ CachePut applies to methods that update data.

    /**
     * 内部员工缓存信息
     * @param phone
     * @param status
     * @param b
     * @param messge
     * @return
     */
    @CachePut(value = "member#PT5M", key = "'employee:' + #phone")
    public Map<String, Object> employee(String phone,String status , boolean b ,String messge ) {
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("phone", phone);
        resMap.put("status", status); 
        resMap.put("flag",  b);
		resMap.put("messge",messge);
        return resMap;
    }


 

Guess you like

Origin blog.csdn.net/dongjing991/article/details/130343627