In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of SpringBoot integration Redis case analysis, the content is detailed and easy to understand, the operation is simple and quick, and has a certain reference value. I believe you will gain something after reading this SpringBoot integration Redis case analysis article. Let's take a look at it.
If you don't have Redis, download it first.
Download the path cmd, and then the redis-server.exe redis.windows.conf command can start the server
After the service is started, the later ones can be integrated.
Click redis-cli.exe under the redis directory to view the test results. The basic operations are as follows
Key *: view storage content
Flushdb: empty the database
If redis is not familiar with it, look at it.
Undefined
SpringData is also a project as famous as SpringBoot!
Note: after SpringBoot2.x, the original jedis is replaced with lettuce
Jedis: the use of direct connection, multi-thread operation, is not safe, if you want to avoid unsafe, use jedis pool connection pool! [similar to BIO: synchronous blocking IO]
Lettuce: with netty [asynchronous request, higher performance], instances can be shared among multiple threads, and there is no thread unsafe situation! You can reduce the number of threads [similar to NIO: synchronous non-blocking IO]
Asynchronous requests generally require serialization
Source code analysis:
Source code location:
@ Bean / / when the Bean does not exist, the class takes effect / / which means that we can define our own redisTemplate to replace the default! @ ConditionalOnMissingBean (name = "redisTemplate") @ ConditionalOnSingleCandidate (RedisConnectionFactory.class) public RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory) {/ / default RedisTemplate does not have too many settings, redis, objects need to be serialized! / / both generics are Object types, which we need to cast later: the type we need is RedisTemplate template = new RedisTemplate (); template.setConnectionFactory (redisConnectionFactory); return template } @ Bean @ ConditionalOnMissingBean / / since String is the most commonly used type of Redis, a separate Bean @ ConditionalOnSingleCandidate (RedisConnectionFactory.class) public StringRedisTemplate stringRedisTemplate (RedisConnectionFactory redisConnectionFactory) {StringRedisTemplate template = new StringRedisTemplate (); template.setConnectionFactory (redisConnectionFactory); return template;} hands-on test [default RedisTemplate understanding] 1. Import depends on org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-data-redis io.lettuce lettuce-core redis.clients jedis2. Configure all configuration classes for connection # SpringBoot There is an automatic configuration class RedisAutoConfiguration# automatic configuration class that binds a properties configuration file RedisPropertiesspring: redis: host: 127.0.0.1 # Redis server connection port port: 6379 # Redis database index (default is 0) database: 0 # Redis server connection password (default is empty) password: # maximum number of connections to the connection pool (use negative values) (indicates no limit) pool: max-active: 200 # connection pool maximum blocking wait time (using a negative value for no limit) max-wait:-1 # maximum idle connection in the connection pool max-idle: 10 # minimum idle connection in the connection pool min-idle: 0 # connection timeout (milliseconds) timeout: 10003. test
In actual development, we don't write code in this native way.
Generally speaking, we will write these commonly used operations into utility classes: redisUtils [later]
There are jdbcUtils and MybatisUtils ahead.
@ SpringBootTestclass Redis03SpringbootApplicationTests {/ / inject the class @ Autowired public RedisTemplate redisTemplate configured in RedisAutoConfiguration @ Test void contextLoads () {/ / redisTemplate: operate our database Api is the same as ours / / opsForValue: operation string is similar to String / / opsForList: operate List / / except for basic operations, our commonly used methods can operate directly through redisTemplate / / such as transactions and basic CRUD / / get the connection object of redis You can operate the connection to the database [rarely used] / * RedisConnection connection = redisTemplate.getConnectionFactory (). GetConnection () Connection.flushDb (); connection.flushAll (); * / redisTemplate.opsForValue (). Set ("kami", "g1x"); System.out.println (redisTemplate.opsForValue (). Get ("kami"));}} 4. Result
Problem: when writing to Chinese, springboot is normal, but running keys * from the redis.cli.exe in redis will lead to garbled code.
Solution: the default RedisTemplate does not have too many settings, redis, objects need to be serialized!
This is the default serialization configuration
The default serialization method is JDK serialization
6. At this point, we need to write the configuration class ourselves.
After you write it yourself, the default RedisTemplate will become invalid.
Create a config
@ Configurationpublic class RedisConfig {/ / write our own RedisTemplate @ Bean public RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory) {RedisTemplate template = new RedisTemplate (); / / see template.setConnectionFactory (redisConnectionFactory); return template;}}.
Hands-on test [the actual use of custom RedisTemplate--] 1. First create a pojo,user// to turn it into a component, making it easy to call @ Component@Data@AllArgsConstructor@NoArgsConstructorpublic class User {private String name; private Integer age;} 2. Test class writes serialization json object operation [here default serialization is JDK serialization] @ Test public void test () throws JsonProcessingException {/ / Real development generally uses json to pass objects, so serialize jsonUser user = new User ("GE", 3); / / so serialize to json object [becomes json string] String jsonUser = new ObjectMapper () .writeValueAsString (user) RedisTemplate.opsForValue () .set ("user", jsonUser); System.out.println (redisTemplate.opsForValue () .get ("user"));}
If you do not use the above serialization of the json object operation will report an error! String jsonUser = new ObjectMapper () .writeValueAsString (user)
The following is about saving objects, but generally using json objects
Solution: serialize in the entity class [in the enterprise, all our pojo serializes! SpringBoot] / / turn it into a component, making it easy to call @ Component@Data@AllArgsConstructor@NoArgsConstructorpublic class User implements Serializable {private String name; private Integer age;}
3. What we just tested is the default serialization (JDK). At this time, we write other serialization methods ourselves.
Create a config
/ / see Jackson2JsonRedisSerializer objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (); / / configure specific serialization template.setKeySerializer (objectJackson2JsonRedisSerializer).
Multiple serialization methods
An example of writing
It's hard to write by yourself, just use the examples you've already written.
There are different places in the connection, import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;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.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer; import java.rmi.UnknownHostException in the replication connection / * * @ author zhangzhixi * / @ Configurationpublic class RedisConfig {@ Bean @ SuppressWarnings ("all") public RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {/ / Custom String Object RedisTemplate template = new RedisTemplate (); template.setConnectionFactory (redisConnectionFactory); / / Json serialization configuration Jackson2JsonRedisSerializer objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); / / ObjectMapper translation ObjectMapper objectMapper = new ObjectMapper () ObjectMapper.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); objectJackson2JsonRedisSerializer.setObjectMapper (objectMapper); / / serialization of String StringRedisSerializer stringRedisSerializer = new StringRedisSerializer (); / / key uses the serialization method of String template.setKeySerializer (stringRedisSerializer); / / key of hash also uses the serialization method of String template.setHashKeySerializer (stringRedisSerializer) / / value serialization uses jackson template.setValueSerializer (objectJackson2JsonRedisSerializer); / / value of hash adopts jackson template.setHashValueSerializer (objectJackson2JsonRedisSerializer); template.afterPropertiesSet (); return template;}}
You can use it directly in the enterprise.
Write tool classes
Package com.kami.utils;/** * @ author zhangzhixi * @ date 23:33 on 2021-3-1 * / import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Component;import org.springframework.util.CollectionUtils;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;/** * @ author mxz * / @ Componentpublic final class RedisUtil {@ Autowired private RedisTemplate redisTemplate / * specify cache expiration time * * @ param key key * @ param time time (seconds) * @ return * / 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 expiration time according to key * * @ param key key (cannot be Null) * @ return time (seconds) return 0 means permanent validity * / public long getExpire (String key) {return redisTemplate.getExpire (key, TimeUnit.SECONDS) } / * determine whether key exists * * @ param key key (cannot be Null) * @ return true does not exist false does not exist * / public boolean hashKey (String key) {try {return redisTemplate.hasKey (key);} catch (Exception e) {e.printStackTrace (); return false }} / * * delete cache * * @ param key can pass a value or multiple * / public void del (String...) Key) {if (key! = null & & key.length > 0) {redisTemplate.delete (key [0]);} else {redisTemplate.delete (CollectionUtils.arrayToList (key)) }} / / = = String== / * ordinary cache acquires * * @ param key key * @ return value * / public Object get (String key) {return key = = null? Null: redisTemplate.opsForValue (). Get (key);} / * * ordinary cache put in * * @ param key key * @ param value value * @ return true success false failed * / public boolean set (String key, Object value) {try {redisTemplate.opsForValue () .set (key, value); return true } catch (Exception e) {e.printStackTrace (); return false }} / * ordinary cache put and set time * * @ param key key * @ param value value * @ param time time (seconds) time > 0 if time 0) {redisTemplate.opsForValue (). Set (key, value, time, TimeUnit.SECONDS);} else {set (key, value) } return true;} catch (Exception e) {e.printStackTrace (); return false;}} / * * incremental * * @ param key key * @ param delta to add several (greater than 0) * @ return * / public long incr (String key, long delta) {if (delta)
< 0) { throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 * * @param key 键 * @param delta 要减少几(小于0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().decrement(key, delta); } // ================================Map================================= /** * HashGet * * @param key 键 不能为null * @param item 项 不能为null */ public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 获取hashKey对应的所有键值 * * @param key 键 * @return 对应的多个键值 */ public Map hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * * @param key 键 * @param map 对应多个键值 */ public boolean hmset(String key, Map map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet 并设置时间 * * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败 */ public boolean hmset(String key, Map map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time >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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.