Spring-integrated Redis operations are almost always within the redistemplate.
For example, Spring boot has been
Configuration in Properties file again
Parameters for Redis
spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=redispassspring.redis.database= 0spring.redis.timeout=5000
Then add the following code to the application startup class:
@Bean public redistemplate<string, object> redistemplate (redisconnectionfactory redisconnectionfactory) { jackson2jsonredisserializer<object> Jackson2jsonredisserializer = new jackson2jsonredisserializer<object& gt; (Object.class); Objectmapper om = new Objectmapper (); Om.setvisibility (Propertyaccessor.all, JsonAutoDetect.Visibility.ANY); Om.enabledefaulttyping (ObjectMapper.DefaultTyping.NON_FINAL); Jackson2jsonredisserializer.setobjectmapper (OM); redistemplate<string, object> template = new redistemplate<string, object> (); Template.setconnectionfactory (redisconnectionfactory); Thread-Safe Connection Engineering Template.setkeyserializer (Jackson2jsonredisserializer); The key serialization method uses Fastjson Template.setvalueserializer (Jackson2jsonredisserializer); Value serialization mode Template.sethashkeyserializer (Jackson2jsonredisserializer); Template.sethashvalueserializer (Jackson2jsonredisserializer); Template.afterPropertiesset (); return template; }
This allows you to use automatic injection (@Autowired) to get redistemplate operations Redis when needed:
@Autowiredprivate redistemplate<string, string> redistemplate; @Overridepublic Result Selectuserbyid (String ID) {if (Stringutils.isempty (ID)) {throw new businessexception (CommonConstants.ErrorCode.ERROR_ILLEGAL_PARAMTER);// ID is null}string rediscache = Redistemplate.opsforvalue (). get (Cachekeys.select_user_phone_keys+id); if (redisCache!=null {result result = new Gson (). Fromjson (Rediscache, Result.class); if (result.getresult () = = null) {throw new Businessexception (CommonConstants.ErrorCode.ERROR_ILLEGAL_USER);//user does not exist}return result;} User Selectbyprimarykey = Usermapper.selectbyprimarykey (ID); The DAO layer of your own project Redistemplate.opsforvalue (). Set (Cachekeys.select_user_phone_keys+id, CommonConstants.GSONIGNORENULL.toJson (New Result (Selectbyprimarykey)), 1, timeunit.hours); Cache validity time is 1 days if (Selectbyprimarykey = = null) {throw new Businessexception (CommonConstants.ErrorCode.ERROR_ILLEGAL_USER );//user does not exist}return new Result (Selectbyprimarykey);}
Spring's Redis operations class Redistemplate