Overview
Caching is ubiquitous in our daily project development because it can greatly improve the system's access speed, and there are a wide variety of frameworks for caching, and today the main focus is to use the now very popular NoSQL database (Redis) to implement our caching needs.
About Redis
Redis is an open-source (BSD-licensed), in-memory data structure storage system that can be used as a database, cache, and message middleware, and the benefits of Redis include its speed, support for rich data types, operational atomicity, and its versatility.
Case integration
This case is based on the previous Springboot + Mybatis + RESTful Foundation to integrate Redis, so if you do not understand the place can go to https://my.oschina.net/feinik/blog/ 879266, because of the length of the reasons here do not post all the code, the specific complete case code can be seen here: https://github.com/AIFEINIK/SpringBoot-Learn/tree/master/ Spring-boot-redis2, about how Redis installs can be self-Google.
1. Add Redis package to maven Pom.xml file
<!--redis--><dependency> <groupId>org.springframework.boot</groupId> <artifactId> Spring-boot-starter-redis</artifactid> <version>${boot.version}</version></dependency>
2. Configure Redis Connection in Springboot configuration file (Yaml mode configuration)
spring: application: name: spring-boot-redis redis: host: 192.168.145.132 port: 6379 timeout: 20000 cluster: nodes: 192.168.211.134:7000,192.168.211.134:7001,192.168.211.134:7002 maxRedirects: 6 pool: max-active: 8 min-idle: 0 max-idle: 8 &nbsP; max-wait: -1
Explanation: This configuration uses Redis a master three-way configuration to increase the throughput of the cache
3. Redis Configuration Class
@Configurationpublic class RedisConfig { @Bean public Redistemplate<object, object> redistemplate (Redisconnectionfactory connectionfactory) { RedisTemplate<Object, Object> template = New redistemplate<> (); template.setconnectionfactory ( ConnectionFactory) //use Jackson2jsonredisserializer to serialize and deserialize the value values of Redis Jackson2JsonRedisSerializer serializer = new Jackson2jsonredisserializer (object.class); objectmapper mapper = new objectmapper (); mapper.setvisibility (PropertyAccessor.ALL, jsonautodetect.visibility.any); mapper.enabledefaulttyping ( ObjectMapper.DefaultTyping.NON_FINAL); &nBsp; serializer.setobjectmapper (Mapper); Template.setvalueserializer (serializer); // Use Stringredisserializer to serialize and deserialize the key value of Redis template.setkeyserializer (new stringredisserializer ()); template.afterpropertiesset (); return template; }}
Explanation: Springboot provides automatic configuration of Redis, and in Redisautoconfiguration we configure jedisconnectionfactory (client connection) by default, Redistemplate and stringredistemplate (data manipulation templates), where the stringredistemplate template operates only on data that is character-based for key-value pairs. This example uses redistemplate as the data manipulation template, which defaults to the Jdkserializationredisserializer binary data serialization method. To facilitate demonstration This example uses Jackson2jsonredisserializer to serialize and deserialize the value values of Redis, using Stringredisserializer to serialize and deserialize the Redis key value.
4. Service Layer application cache (annotation mode)
@Servicepublic class PersonService { @Autowired private personrepo personrepo; /** * @Cacheable applied to the method of reading the data, first read from the cache, if no more data from the DB, and then add the data to the cache * unless indicates that the conditional expression is not placed in the cache * @param username * @return */ @Cacheable (value = "User", key = "# root.targetclass + #username ", unless = " #result eq null ") public person getpersonbyname (String username) { person person = personrepo.getpersonbyname (username); return person; } /** * @CachePut &NBSP; Apply to write data method, such as new/modify method, call method will automatically put the corresponding data into the cache * @param person * @return */ @CachePut (value = "User", key = "#root .targetclass + #result. Username", unless = " #person eq null ") public person saveperson (Person person) { return personrepo.saveperson (person); } /** * @CacheEvict Apply to the method of deleting data, The data for the corresponding key is removed from the cache when the method is called * @param username * @return */ @CacheEvict (value = "User", key = "#root .targetclass + #username", condition = "#result eq true ") public boolean removepersonbyname (String username) { return personrepo.removepersonbyname (username) > 0; } public boolean isexistpersonname (Person person) { return personrepo.existpersonname (person) > 0; }}
Explain:
1, the cache key here is a simple string combination, you can also implement the custom key generator according to the specific needs, and then use Keygenerator to reference in the annotations.
2. Spring cache provides some spel contextual data for our use, which can be referenced by # to see the spring website: http://docs.spring.io/spring/docs/current/ spring-framework-reference/htmlsingle/#cache-spel-context.
5. Data Access Resource class
@Component @path ("Personmgr") public class personmgrresource { @Autowired private PersonService personService; @GET @Path ("Getpersonbyname") @Produces (Mediatype.application_json) public jsonresp getpersonbyname (@QueryParam ("username") string username) { person person = personservice.getpersonbyname ( username); return jsonresp.success (person); } @POST @Path ("Removepersonbyname") @Produces (Mediatype.application_json) public JsonResp Removepersonbyname (@QueryParam ("username") string username) { if (personseRvice.removepersonbyname (username)) { return jsonresp.success (); } return jsonresp.fail ("System error! "); } @POST @Path (" Saveperson ") @Produces (Mediatype.application_json) public JsonResp Saveperson (Person person) { if ( Personservice.isexistpersonname (person)) { return jsonresp.fail ("User name already exists!") "); } if ( Personservice.saveperson (person). GetId () > 0) { return jsonresp.sUccess (); } Return jsonresp.fail ("System error! "); }}
6. Use Postman tool to test whether the cache is in effect
First-time access to find users:
The first time a user name is used to find the data that the user can see is queried from the library, we can see that the data has been put into the cache through the Redisclient tool.
Second Lookup User: The discovery server does not print any database query logs, you can know that the second query is the data from the cache query.
Summarize
This article describes how to integrate the Redis cache step-by-step with Springboot, which can be used not only as a cache, but also as a queue system, pub/sub real-time messaging systems, distributed system counter applications, and more about Redis, Please refer to the official documentation.
Article Source: https://my.oschina.net/feinik/blog/1023601
Springboot integrated Redis for caching technology Solutions