Based on the spring Boot 1.5.2.RELEASE version, the integration approach to Redis is verified on the one hand, and the method of use is also known.
Integration method
- The
-
Configuration relies on
Modify pom.xml
to add the following content.
< Dependency ; <groupid ; Org.springframework.boot</groupid ; <artifactid ; Spring-boot-starter-data-redis</artifactid ; </dependency ;
Configure Redis
Modify application.yml
, add the following content.
spring: redis: host: localhost 6379 pool: max-idle8 min-idle0 max-active8 max-wait-1
Configuring the Redis Cache
PackageNet.jackieathome.cache;ImportJava.lang.reflect.Method;ImportOrg.springframework.cache.CacheManager;ImportOrg.springframework.cache.annotation.CachingConfigurerSupport;Importorg.springframework.cache.annotation.EnableCaching;ImportOrg.springframework.cache.interceptor.KeyGenerator;ImportOrg.springframework.context.annotation.Bean;ImportOrg.springframework.context.annotation.Configuration;ImportOrg.springframework.data.redis.cache.RedisCacheManager;ImportOrg.springframework.data.redis.connection.RedisConnectionFactory;ImportOrg.springframework.data.redis.core.RedisTemplate;ImportOrg.springframework.data.redis.core.StringRedisTemplate;ImportOrg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;ImportCom.fasterxml.jackson.annotation.JsonAutoDetect;ImportCom.fasterxml.jackson.annotation.PropertyAccessor;ImportCom.fasterxml.jackson.databind.ObjectMapper;@Configuration@EnableCaching //Enable caching features Public class redisconfig extends cachingconfigurersupport { //cache data when key generator, can be customized according to business and technical scenarios//@Bean//Public keygenerator Customizedkeygenerator () {//return new Keygenerator () {//@Override//public object generate (object target, Method method, Object ... params) {//StringBuilder SB = new StringBuilder ();//Sb.append (Target.getclass (). GetName ());//Sb.append (Method.getname ());//For (Object obj:params) {//Sb.append (obj.tostring ());// }//return sb.tostring ();// }// };//// } //Custom Cache manager Properties, default supplied CacheManager object may not meet the needs //It is therefore recommended to rely on business and technical requirements to do some scaling and customization on your own @Bean PublicCacheManagerCacheManager(@suppresswarnings("Rawtypes") Redistemplate redistemplate) {Rediscachemanager Rediscachemanager =NewRediscachemanager (redistemplate); Rediscachemanager.setdefaultexpiration ( -);returnRediscachemanager; }@Bean PublicRedistemplate<string, string>redistemplate(Redisconnectionfactory Factory) {Stringredistemplate template =NewStringredistemplate (Factory); Jackson2jsonredisserializer Jackson2jsonredisserializer =NewJackson2jsonredisserializer (Object.class); Objectmapper om =NewObjectmapper (); Om.setvisibility (Propertyaccessor.all, JsonAutoDetect.Visibility.ANY); Om.enabledefaulttyping (ObjectMapper.DefaultTyping.NON_FINAL); Jackson2jsonredisserializer.setobjectmapper (OM); Template.setvalueserializer (Jackson2jsonredisserializer); Template.afterpropertiesset ();returnTemplate }}
Verifying the effects of integration
Considering that future participating projects implement database access based on MyBatis, and the use of caching can effectively improve the interactive experience of Web pages, the following two verification schemes are designed.
Programme I
Add cache annotations on the data objects that access the database, and define the cache policy. From the test effect, the cache is valid.
Page Controller
PackageNet.jackieathome.controller;ImportJava.util.List;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.web.bind.annotation.PathVariable;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.bind.annotation.RestController;ImportNet.jackieathome.bean.User;ImportNet.jackieathome.dao.UserDao;ImportNet.jackieathome.db.mapper.UserMapper;@RestController Public class usercontroller { @Autowired PrivateUserdao Userdao;@RequestMapping(method = Requestmethod.get, value ="/user/id/{id}") PublicUserFinduserbyid(@pathvariable("id") String ID) {returnUserdao.finduserbyid (ID); }@RequestMapping(method = Requestmethod.get, value ="/user/create") PublicUserCreateUser() {LongTime = System.currenttimemillis ()/ +; String ID ="id"+ Time; User User =NewUser (); User.setid (ID); Userdao.createuser (user);returnUserdao.finduserbyid (ID); }}
Mapper definition
PackageNet.jackieathome.db.mapper;ImportJava.util.List;ImportOrg.apache.ibatis.annotations.Mapper;ImportOrg.apache.ibatis.annotations.Param;ImportOrg.springframework.cache.annotation.CacheConfig;ImportOrg.springframework.cache.annotation.CachePut;Importorg.springframework.cache.annotation.Cacheable;ImportNet.jackieathome.bean.User;@Mapper Public interface usermapper { voidCreateUser (user user); User Finduserbyid (@Param("id") String ID);}
Data Access Objects
PackageNet.jackieathome.dao;ImportJava.util.ArrayList;ImportJava.util.List;ImportOrg.apache.ibatis.annotations.Param;ImportOrg.slf4j.Logger;ImportOrg.slf4j.LoggerFactory;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.cache.annotation.CacheConfig;ImportOrg.springframework.cache.annotation.CachePut;Importorg.springframework.cache.annotation.Cacheable;ImportOrg.springframework.stereotype.Component;Importorg.springframework.transaction.annotation.Transactional;ImportNet.jackieathome.bean.User;ImportNet.jackieathome.db.mapper.UserMapper;@Component@CacheConfig(Cachenames ="Users")@Transactional Public class Userdao { Private Static FinalLogger LOG = Loggerfactory.getlogger (Userdao.class);@Autowired PrivateUsermapper Usermapper;@CachePut(key ="#p0. ID") Public void CreateUser(User user) {usermapper.createuser (user); Log.debug ("Create user="+ user); }@Cacheable(key ="#p0") PublicUserFinduserbyid(@Param("id") String ID) {Log.debug ("Find user="+ ID);returnUsermapper.finduserbyid (ID); }}
Programme II
Add cache annotations directly to the mapper definition and control caching policies. From the test effect, the cache is effective, compared to scenario one, the test code is more concise.
Page Controller
PackageNet.jackieathome.controller;ImportJava.util.List;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.web.bind.annotation.PathVariable;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.bind.annotation.RestController;ImportNet.jackieathome.bean.User;ImportNet.jackieathome.dao.UserDao;ImportNet.jackieathome.db.mapper.UserMapper;@RestController Public class usercontroller { @Autowired PrivateUsermapper Usermapper;@RequestMapping(method = Requestmethod.get, value ="/user/id/{id}") PublicUserFinduserbyid(@pathvariable("id") String ID) {returnUsermapper.finduserbyid (ID); }@RequestMapping(method = Requestmethod.get, value ="/user/create") PublicUserCreateUser() {LongTime = System.currenttimemillis ()/ +; String ID ="id"+ Time; User User =NewUser (); User.setid (ID); Usermapper.createuser (user);returnUsermapper.finduserbyid (ID); }}
Mapper definition
PackageNet.jackieathome.db.mapper;ImportJava.util.List;ImportOrg.apache.ibatis.annotations.Mapper;ImportOrg.apache.ibatis.annotations.Param;ImportOrg.springframework.cache.annotation.CacheConfig;ImportOrg.springframework.cache.annotation.CachePut;Importorg.springframework.cache.annotation.Cacheable;ImportNet.jackieathome.bean.User;@CacheConfig(Cachenames ="Users")@Mapper Public interface usermapper { @CachePut(key ="#p0. ID")voidCreateUser (user user);@Cacheable(key ="#p0") User Finduserbyid (@Param("id") String ID);}
Summarize
The above two test schemes do not have the merits and demerits, only in order to verify the use of caching methods, embodies the different control granularity, in the actual project development process, need to make different decisions according to the actual situation.
Cache-related annotations:
- CacheConfig
- Cacheable
- Cacheput
- Cacheevict
Resources using the Redis cache
- Caching
- Spring-boot/spring-boot-samples/spring-boot-sample-cache
- Caching Data in Spring Using Redis
- Spring Boot uses Redis to do data caching
- Spring-boot using Redis as a caching service
- Cache support in Spring boot (ii) using Redis for centralized caching
- Spring Boot uses Redis to do data caching
- Configure Redis cache under Spring boot
MyBatis Caching Features
- MyBatis Ehcache adapter-reference Documentation
- Mapper XML File
- Use and understanding of MyBatis cache
- MyBatis Cache
- MyBatis caching mechanism deep anatomy/Custom Level two cache
- MyBatis caching configuration (cache)
- MyBatis Two-level caching principle
- mybatis-Transformation Cache
- MyBatis cache mechanism (cache level two cache and refresh cache) and MyBatis consolidation Ehcache
- The design and implementation of MyBatis caching mechanism in the deep understanding of mybatis principle
- "In-depth understanding mybatis principle" design principle of the level two cache of MyBatis
- MyBatis Basics of Entry (eight)-query cache
Other
Commands to run a Redis docker image
sudo-d6379:6379 redis
View Original http://www.jackieathome.net/archives/485.html
Spring Boot uses Redis for data caching