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

SpringBoot Learning (7)-- springboot Rapid Integration of Redis

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

Redis caching

@ [toc]

Brief introduction

Redis is a high performance key-value database

advantage

Strong performance, suitable for high read and write operations (read speed is 110000 times / s, write speed is 81000 times / s).

Supports rich data types (such as binary Strings, Lists, Hashes, Sets, Ordered Sets)

A certain ability to do things (either successfully or not at all). Disadvantage memory database access is fast, but it also consumes hardware memory resources

Note: redis's single thread simply says that the client's request is processed with a request on the network request module, but for example, persisting it will restart a thread / process to process.

Introducing redis caching

Click the link to download the window version of redis. After downloading, put it in the location where you usually put the software, decompress it and install it. (it should be noted that if the current user has read and write permissions, such as C:\ Program Files (x86) under window, this directory can only be read and written by administrator by default. If redis runs to write log files in this directory in real time, if there is no read and write permission, the operation will not be successful.)

The extracted directory is shown below. Because it is on the exe side, you can double-click the Windows file to open the client side and the server side.

Because this is the springboot integrated redis series, double-click to open the server, do not close the open cmd window.

Add to pom.xml

Org.springframework.boot spring-boot-starter-data-redis

Add in application.properties

# Redis#Redis server address spring.redis.host=127.0.0.1#Redis server connection port spring.redis.port=6379# Redis server connection password (default is empty) spring.redis.password=#Redis database index (default is 0) spring.redis.database=0 # maximum number of connections in connection pool (use negative values for no limit) maximum blocking wait time in spring.redis.jedis.pool.max-active=50# connection pool (use Negative value means no limit) maximum idle connection in spring.redis.jedis.pool.max-wait=3000# connection pool minimum idle connection spring.redis.jedis.pool.min-idle=5# connection timeout in spring.redis.jedis.pool.max-idle=20# connection pool (Ms) spring.redis.timeout=4000 code

The directory after the new code is as follows

Here we first explain the role of the main class. Springboot provides the RedisTemplate class to manipulate Redis, but this class has no annotated interpretation, and the naming rules are not literal enough. So write a RedisUtil to encapsulate some commonly used methods, RedisConfig is mainly to change the default automatic injection to manual injection and add serialization to avoid some Chinese garbled problems.

In particular, let's talk about the RedisUtil class, searching for springboot and redis articles. Most of the classes that need to be encapsulated by themselves are very chaotic, and the encapsulation logic before and after is inconsistent. I guess it was copied and pasted by a blogger from at least three people, and then everyone copied and pasted with this blogger, which became a hot article instead. I guess it is a tool class, and it is about 600 lines, and most of them have not thought about it carefully and can simply pass the test, but after a little thinking, I find that there are really a lot of problems, and it is easy to mislead those who like "borrowlism".

Although my series is also a quick start series, the quick start that I understand is to speak bluntly the concepts that make people foggy, and then temporarily skip those that need to be in depth and avoid the fear of difficulties that have just started. Write the whole operation flow clearly and tell others 10,000 sentences a thousand times. It's better to let him run against the ready-made program. I always think: learn the program against a blank screen. It will only make people more anxious, and the best way is to go deep while running.

So I chose the String,Hash,Set,List of the five types of redis, covering almost each type, while SortedSet did not choose because it is an ordered Set, which can be compared by itself. What I uniformly provide is to take values, add values, delete values, and naming rules can definitely make you "literal". In fact, there are many methods. I don't write all of them here, because there are a bunch of methods for the five big data types, which you may not necessarily use, and they take up a lot of space. here, it is better to teach people to fish than to teach people to fish. If you take a closer look at the tools of RedisUtil, you will find rules, such as operating String. Most of them first call the opsForValue () method and operate Hash, and most of them first call the opsForHash () method to download the project code locally, click inside the idea, and you can see a bunch of related methods. The utility class is just called again, changed its name, and added some logic processing.

Don't follow blindly if it's a hot article. Let me cite a few of the questions I just mentioned.

There is also this note that the style is not uniform, it gives people the impression that it is easy to be foggy, and all the tools on the Internet are still used in this one. It is really hard to laugh or cry. Everyone copies them around, and they are all scheme integrators, so don't …...

Let's start the code demonstration.

RedisController.java

Package com.example.controller;import com.example.service.IRedisService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping ("redis") public class RedisController {@ Autowired private IRedisService redisService; @ RequestMapping ("/ redisString") public void redisString () {this.redisService.redisString () } @ RequestMapping ("/ redisHash") public void redisHash () {this.redisService.redisHash ();} @ RequestMapping ("/ redisSet") public void redisSet () {this.redisService.redisSet ();} @ RequestMapping ("/ redisList") public void redisList () {this.redisService.redisList () } @ RequestMapping ("/ redisSortedSet") public void redisSortedSet () {/ / ordered set, so omit}}

IRedisService.java

Package com.example.service;public interface IRedisService {void redisString (); void redisHash (); void redisSet (); void redisList (); void redisSortedSet ();}

RedisServiceIml.java

Package com.example.service;import com.example.util.RedisUtil;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.util.List;import java.util.Set;@Service ("redisService") public class RedisServiceIml implements IRedisService {@ Autowired private RedisTemplate redisTemplate; @ Resource private RedisUtil redisUtil Public void redisString () {/ / add value redisUtil.stringSet ("AAA", "this is a value of type String"); / / value Object value = redisUtil.stringGet ("AAA"); System.out.println (value);} public void redisHash () {/ / add value redisUtil.hashSet ("BBB", "test1", "original hash value 1") RedisUtil.hashSet ("BBB", "test2", "new hash value 1"); redisUtil.hashSet ("BBB", "test1", "original hash value 2"); redisUtil.hashSet ("BBB", "test2", "new hash value 2"); / / values Object value1 = redisUtil.hashGet ("BBB", "test1"); Object value2 = redisUtil.hashGet ("BBB", "test2") System.out.println (value1); System.out.println (value2);} public void redisSet () {/ / add redisUtil.setSet ("CCC", "this is the first of a set of Set collections"); redisUtil.setSet ("CCC", "this is the second of a set of Set collections"); redisUtil.setSet ("CCC", "this is the third of a set of Set collections") / / value Set vaule = redisUtil.setGet ("CCC"); System.out.println (vaule);} public void redisList () {/ / add the value redisUtil.listSet ("DDD", "this is the first of a set of List sets"); redisUtil.listSet ("DDD", "this is the second of a set of List sets") RedisUtil.listSet ("DDD", "this is the third of a set of List collections"); / / values List list = redisUtil.listGet ("DDD", 0,-1); System.out.println (list);} public void redisSortedSet () {/ / ordered set, so omit}}

RedisConfig.java

Package com.example.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.annotation.EnableCaching;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.*;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer Import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration@EnableCachingpublic class RedisConfig extends CachingConfigurerSupport {@ Bean public RedisTemplate redisTemplate (RedisConnectionFactory factory) {RedisTemplate template = new RedisTemplate (); / configure connection factory template.setConnectionFactory (factory); / / serialize and deserialize the value Jackson2JsonRedisSerializer jackson = new Jackson2JsonRedisSerializer (Object.class) in redis; / / Java object is converted to JSON structure ObjectMapper objectMapper = new ObjectMapper () / / specify the domain objectMapper.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY) to be serialized; / / specify the type of serialization input objectMapper.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); jackson.setObjectMapper (objectMapper); / / serialize template.setValueSerializer (jackson) with json / / use StringRedisSerializer to serialize and deserialize the key value of redis template.setKeySerializer (new StringRedisSerializer ()); / / set hash key and value serialization mode template.setHashKeySerializer (new StringRedisSerializer ()); template.setHashValueSerializer (jackson); template.afterPropertiesSet (); return template;}}

RedisUtil.java

Package com.example.util;import java.util.List;import java.util.Set;import java.util.concurrent.TimeUnit;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Component;import org.springframework.util.CollectionUtils;@Componentpublic class RedisUtil {@ Autowired private RedisTemplate redisTemplate / / = cache-related method = / / specify cache expiration time public boolean expire (String key, long time) {try {if (time > 0) {redisTemplate.expire (key, time, TimeUnit.SECONDS);} return true;} catch (Exception e) {e.printStackTrace (); return false }} / / obtain the expiration time according to key, return 0 represents permanent valid public long getExpire (String key) {return redisTemplate.getExpire (key, TimeUnit.SECONDS);} / / = relevant method with data type String = / / get cache value public Object stringGet (String key) {return key = = null? Null: redisTemplate.opsForValue (). Get (key);} / / the cache value public boolean stringSet (String key, Object value) {try {redisTemplate.opsForValue (). Set (key, value); return true;} catch (Exception e) {e.printStackTrace (); return false based on the key value }} / / according to the key value, store the cache value of data type String and set the time public boolean stringSetWithTime (String key, Object value, long time) {try {if (time > 0) {redisTemplate.opsForValue (). Set (key, value, time, TimeUnit.SECONDS);} else {expire (key, time) } return true;} catch (Exception e) {e.printStackTrace (); return false;}} / / Delete cache public void stringDelete (String... Key) {if (key! = null & & key.length > 0) {if (key.length = = 1) {redisTemplate.delete (key [0]);} else {redisTemplate.delete (CollectionUtils.arrayToList (key)) } / / = related methods with data type Hash = / / get the cache value public Object hashGet (String key, String item) {return redisTemplate.opsForHash (). Get (key, item) based on key and item } / / according to key and item, the cache value public boolean hashSet (String key, String item, Object value) {try {redisTemplate.opsForHash (). Put (key, item, value); return true;} catch (Exception e) {e.printStackTrace (); return false }} / / according to key and item, store the cache value of data type Hash and set the time public boolean hashSetWithTime (String key, String item, Object value, long time) {try {redisTemplate.opsForHash (). Put (key, item, value); if (time > 0) {expire (key, time);} return true } catch (Exception e) {e.printStackTrace (); return false;}} / / Delete cache public void hashDelete (String key, Object...) Item) {redisTemplate.opsForHash (). Delete (key, item);} / / related methods with data type SET = / / get the cache value public Set setGet (String key) {try {return redisTemplate.opsForSet (). Members (key);} catch (Exception e) {e.printStackTrace (); return null }} / / the cache value public long setSet (String key, Object...) with the data type SET is stored according to the key value Values) {try {return redisTemplate.opsForSet () .add (key, values);} catch (Exception e) {e.printStackTrace (); return 0;}} / / stores the cache value of data type SET based on the key value and sets the public long setSetWithTime (String key, long time, Object...) Values) {try {Long count = redisTemplate.opsForSet (). Add (key, values); if (time > 0) {expire (key, time);} return count;} catch (Exception e) {e.printStackTrace (); return 0 }} / / delete cache public long setDelete (String key, Object...) Values) {try {Long count = redisTemplate.opsForSet (). Remove (key, values); return count;} catch (Exception e) {e.printStackTrace (); return 0 }} / / = related methods with data type LIST = / / get the contents of List cache from start to end, if 0 to-1 represents all values public List listGet (String key, long start, long end) {try {return redisTemplate.opsForList (). Range (key, start, end);} catch (Exception e) {e.printStackTrace (); return null }} / / according to the key value, the cache value public boolean listSet (String key, Object value) {try {redisTemplate.opsForList (). RightPush (key, value); return true;} catch (Exception e) {e.printStackTrace (); return false }} / / according to the key value, store the cache value of data type List and set the time public boolean listSetWithTime (String key, Object value, long time) {try {redisTemplate.opsForList () .rightPush (key, value); if (time > 0) {expire (key, time);} return true } catch (Exception e) {e.printStackTrace (); return false;}} / / delete cache public long listDelete (String key, long count, Object value) {try {Long remove = redisTemplate.opsForList (). Remove (key, count, value); return remove;} catch (Exception e) {e.printStackTrace () Return 0;}

After starting the project, the browser enters http://localhost:8080/redis/redisString. (the foreground will report an error because the request only triggers the business logic in the background and is not displayed on the foreground page.) the effect of the operation String type is shown below.

After starting the project, the browser enters http://localhost:8080/redis/redisHash, and the effect of operating the Hash type is shown below; (note that my previous code inserted four values and only printed two, because if the key value is the same as the item value, the new value will overwrite the original value, compare the picture and the code, you product, you detail. )

After starting the project, enter http://localhost:8080/redis/redisSet in the browser, and the effect of manipulating the Set type is shown below; (Set is unordered)

After starting the project, enter http://localhost:8080/redis/redisList in the browser, and the effect of manipulating the List type is as follows

Note: if you are based on this article series, remember to assign this address to the logged-in user because spring security is configured at the beginning. Or open a Super Admin account that can access any directory of the project and use the administrator account to access these addresses.

This is all the code of the learning series. If there is anything you don't understand, if you want to enrich it, you can download it locally.

GitHub, Ma Yun

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

Internet Technology

Wechat

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

12
Report