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)06/02 Report--
This article is to share with you about how Spring Boot integrates Redis. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Brief introduction to Redis what is Redis
Redis is a widely used free and open source memory database, which is a high-performance key-value database.
Compared with other key-value caches, such as Memcached, Redis has the following three characteristics:
1.Redis supports the persistence of data. It can save the data in memory on disk and load it again when restarting. 2.Redis not only supports simple key-value type data, but also provides storage of data structures such as list,set,zset,hash. 3.Redis supports data backup, that is, data backup in master-slave mode.
Redis has the following advantages:
1. The performance is extremely high. Redis can read at a speed of 110000 times per second and write at a speed of 81000 times per second. two。 Rich data types. Redis supports Strings,Lists,Sets and Ordered Sets data type manipulation for binary cases. 3. Atomicity. All operations in Redis are atomic, meaning either successful execution or failure to execute at all. A single operation is atomic, and so are multiple operations, picked up by MULTI and EXEC instructions. 4. Rich features. Redis also supports publish/subscribe, notification, key expiration and other features.
Spring Boot integrates Redis1. Add dependency 4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.9.RELEASE cn.zwqh spring-boot-redis 0.0.1-SNAPSHOT spring-boot-redis spring-boot-redis to the project 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test Org.springframework.boot spring-boot-starter-data-redis org.springframework.boot Spring-boot-maven-plugin
When viewing the jar package, it is found that there are two packages jedis and lettuce under the org.springframework.data.redis.connection package path under Spring Data Redis by default, which means that Spring Boot has been packaged to adapt to these two Redis clients by default.
In springboot 1.5.x, the default Redis client is implemented by Jedis, while in springboot 2.x, the default client is implemented in lettuce.
Comparison between Lettuce and Jedis
Both Lettuce and Jedis are clients that connect to Redis Server.
Jedis is implemented as a directly connected redis server, which is not thread-safe in a multithreaded environment, unless connection pooling is used to add physical connections to each redis instance.
Lettuce is a scalable, thread-safe, completely non-blocking Redis client. Multiple threads can share a single RedisConnection. It uses the Netty NIO framework to efficiently manage multiple connections, thus providing asynchronous and synchronous data access for building non-blocking reactive applications.
Let's use Lettuce and Jedis to integrate Redis services.
2. Lettuce Integration Redis Service Import dependency
Because Spring Boot 2.x integrates Lettuce by default, there is no need to import.
Application.properties profile # Redis basic configuration # Redis database index (default is 0) spring.redis.database=0 # 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=zwqh# link super Time unit ms (milliseconds) spring.redis.timeout=3000# Redis thread pool setting # connection pool maximum number of connections (use negative values for no limit) default 8spring.redis.lettuce.pool.max-active=8# connection pool maximum blocking wait time (use negative values for no limit) default-1spring .redis.lettuce.pool.max-maximum idle connection in wait=-1# connection pool default 8spring.redis.lettuce.pool.max-idle=8# connection pool minimum idle connection default 0spring.redis.lettuce.pool.min-idle=0 custom RedisTemplate
By default, the template can only support RedisTemplate, can only store strings, many times, we need to customize RedisTemplate, set serializer, so that we can easily manipulate instance objects. As follows:
@ Configurationpublic class LettuceRedisConfig {@ Bean public RedisTemplate redisTemplate (LettuceConnectionFactory connectionFactory) {RedisTemplate redisTemplate = new RedisTemplate (); redisTemplate.setKeySerializer (new StringRedisSerializer ()); redisTemplate.setValueSerializer (new GenericJackson2JsonRedisSerializer ()); redisTemplate.setConnectionFactory (connectionFactory); return redisTemplate }} serialize entity class public class UserEntity implements Serializable {/ * / private static final long serialVersionUID = 5237730257103305078L; private Long id; private String userName; private String userSex; public Long getId () {return id;} public void setId (Long id) {this.id = id } public String getUserName () {return userName;} public void setUserName (String userName) {this.userName = userName;} public String getUserSex () {return userSex;} public void setUserSex (String userSex) {this.userSex = userSex }} Unit Test @ RunWith (SpringRunner.class) @ SpringBootTestpublic class SpringBootRedisApplicationTests {@ Autowired private RedisTemplate strRedisTemplate; @ Autowired private RedisTemplate serializableRedisTemplate; @ Testpublic void testString () {strRedisTemplate.opsForValue () .set ("strKey", "zwqh"); System.out.println (strRedisTemplate.opsForValue () .get ("strKey")) } @ Test public void testSerializable () {UserEntity user=new UserEntity (); user.setId (1L); user.setUserName ("misty light cold"); user.setUserSex ("male"); serializableRedisTemplate.opsForValue () .set ("user", user) UserEntity user2 = (UserEntity) serializableRedisTemplate.opsForValue (). Get ("user"); System.out.println ("user:" + user2.getId () + "," + user2.getUserName () + "," + user2.getUserSex ());}}
The implementation results are as follows: we get the expected results.
3.Jedis Integration Redis Service pom File 4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.9.RELEASE cn.zwqh spring-boot-redis 0.0.1-SNAPSHOT spring-boot-redis spring-boot-redis 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test Test org.springframework.boot spring-boot-starter-data-redis Io.lettuce lettuce-core redis.clients jedis Org.springframework.boot spring-boot-maven-plugin application.properties profile # Redis Basics Configure # Redis database index (default is 0) spring.redis.database=0 # 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=zwqh# link timeout unit ms (millisecond) spring.redis.timeout=3000# # Redis thread pool setting # maximum number of connections in connection pool (using negative values for no limit) default 8spring.redis.jedis.pool.max-active=8# connection pool maximum blocking wait time (using negative values for no limit) default-maximum idle connections in 1spring.redis.jedis.pool.max-wait=-1# connection pool Minimum idle connections in the default 8spring.redis.jedis.pool.max-idle=8# connection pool default 0spring.redis.jedis.pool.min-idle=0JedisRedisConfig@Configurationpublic class JedisRedisConfig {@ Value ("${spring.redis.database}") private int database @ Value ("${spring.redis.host}") private String host; @ Value ("${spring.redis.port}") private int port; @ Value ("${spring.redis.password}") private String password; @ Value ("${spring.redis.timeout}") private int timeout @ Value ("${spring.redis.jedis.pool.max-active}") private int maxActive; @ Value ("${spring.redis.jedis.pool.max-wait}") private long maxWaitMillis; @ Value ("${spring.redis.jedis.pool.max-idle}") private int maxIdle; @ Value ("${spring.redis.jedis.pool.min-idle}") private int minIdle / * * connection pool configuration information * / @ Bean public JedisPoolConfig jedisPoolConfig () {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig (); / / maximum number of connections jedisPoolConfig.setMaxTotal (maxActive) / / maximum waiting time jedisPoolConfig.setMaxWaitMillis (maxWaitMillis) when no connections are available in the pool; / / maximum number of idle connections jedisPoolConfig.setMinIdle (maxIdle); / / minimum number of idle connections jedisPoolConfig.setMinIdle (minIdle) / / you can add return jedisPoolConfig for other attributes. } / * Jedis connection * * @ param jedisPoolConfig * @ return * / @ Bean public JedisConnectionFactory jedisConnectionFactory (JedisPoolConfig jedisPoolConfig) {JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder () .usePooling () .poolConfig (jedisPoolConfig) .and () .readTimeout (Duration.ofMillis (timeout)) .poolConfig () RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration (); redisStandaloneConfiguration.setHostName (host); redisStandaloneConfiguration.setPort (port); redisStandaloneConfiguration.setPassword (RedisPassword.of (password)); return new JedisConnectionFactory (redisStandaloneConfiguration, jedisClientConfiguration) } / * Cache Manager * * @ param connectionFactory * @ return * / @ Bean public RedisCacheManager cacheManager (RedisConnectionFactory connectionFactory) {return RedisCacheManager.create (connectionFactory);} @ Bean public RedisTemplate redisTemplate (JedisConnectionFactory connectionFactory) {RedisTemplate redisTemplate = new RedisTemplate () RedisTemplate.setKeySerializer (new StringRedisSerializer ()); redisTemplate.setValueSerializer (new GenericJackson2JsonRedisSerializer ()); redisTemplate.setConnectionFactory (jedisConnectionFactory (jedisPoolConfig (); return redisTemplate;}} unit test as above
The expected results appear.
The above describes how Spring Boot 2.x integrates Redis services through Lettuce and Jedis, and we can also customize operation classes to implement data operations according to project requirements.
This is how Spring Boot integrates Redis. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
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.