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

The case of using springBoot to integrate redis

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

Editor to share with you the use of springBoot integration of redis cases, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to understand it!

What is springboot? springboot is a new programming specification, which is designed to simplify the initial construction and development process of new Spring applications. SpringBoot is also a framework that serves the framework, and the scope of services is to simplify configuration files.

REmote DIctionary Server (Redis) is a key-value storage system written by Salvatore Sanfilippo.

Redis is an open source log database written in ANSI C language, complies with BSD protocol, supports network, can be memory-based and persistent, Key-Value database, and provides API in multiple languages.

It is often called a data structure server because the value can be of types such as String, Map, list, sets, and sorted sets.

Advantages of reids

Here are some of the advantages of Redis:

Exceptionally fast-Redis is very fast, performing about 110000 set (SET) operations per second and approximately 81000 read / get (GET) operations per second.

Support for rich data types-Redis supports most of the data types commonly used by developers, such as lists, collections, sort sets, hashes, and so on. This makes it easy for Redis to be used to solve a variety of problems because we know which problems can be better used and which data types can be handled.

Operations are atomic-all Redis operations are atomic, which ensures that if two clients access concurrently, the Redis server can receive the updated value.

Multi-utility-Redis is a multi-utility that can be used in a variety of use cases, such as caching, message queuing (Redis natively supports publish / subscribe), any short-term data in the application, such as sessions in web applications, page hit counts, etc.

Redis installation

Install under Window

Download address: https://github.com/MSOpenTech/redis/releases.

Redis supports 32-bit and 64-bit. This needs to be chosen according to the actual situation of your system platform. Here we download the Redis-x64-xxx.zip package to disk C, decompress it, and rename the folder to redis.

Open a cmd window and use the cd command to change directories to C:\ redis

Run redis-server.exe redis.windows.conf

If you want to be convenient, you can add the path of redis to the environment variable of the system, so that you don't have to enter the path again, and the latter redis.windows.conf can be omitted. If omitted, the default will be enabled. After typing, the following interface is displayed:

Integrated redis

Let's extend the project from the previous chapter: Springboot Integration springcloud-config for dataSource Hot deployment

1. Add dependencies

Org.springframework.boot spring-boot-starter-redis 1.4.1.RELEASE com.alibaba fastjson 1.2.3 com.fasterxml.jackson.core jackson-databind

2. Add redis configuration in the configuration center

Spring.redis.host=127.0.0.1#Redis server connection port spring.redis.port=6379#Redis server connection password (default is empty) maximum number of connections in spring.redis.password=# connection pool (using negative values for no limit) maximum blocking wait time in spring.redis.pool.max-active=8# connection pool (use negative values for no limit) maximum idle in spring.redis.pool.max-wait=-1# connection pool Minimum idle connections in the spring.redis.pool.max-idle=8# connection pool spring.redis.pool.min-idle=0# connection timeout (milliseconds) spring.redis.timeout=30000

3. Configuration class RedisConfig

Import java.lang.reflect.Method;import org.springframework.beans.factory.annotation.Value;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.annotation.EnableCaching;import org.springframework.cache.interceptor.KeyGenerator;import org.springframework.cloud.context.config.annotation.RefreshScope;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.connection.RedisConnectionFactory Import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.databind.ObjectMapper;@Configuration@EnableCaching@RefreshScopepublic class RedisConfig extends CachingConfigurerSupport {@ Value ("${spring.redis.host}") private String host @ Value ("${spring.redis.port}") private int port; @ Value ("${spring.redis.timeout}") private int timeout; @ Value ("${spring.redis.password}") private String password; @ Value ("${spring.redis.pool.max-active}") private int maxActive; @ Value ("${spring.redis.pool.max-wait}") private int maxWait @ Value ("${spring.redis.pool.max-idle}") private int maxIdle; @ Value ("${spring.redis.pool.min-idle}") private int minIdle; @ RefreshScope @ Bean public KeyGenerator wiselyKeyGenerator () {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 () }}; @ RefreshScope @ Bean public JedisConnectionFactory redisConnectionFactory () {JedisConnectionFactory factory = new JedisConnectionFactory (); factory.setHostName (host); factory.setPort (port); factory.setTimeout (timeout); / / set connection timeout factory.setPassword (password); factory.getPoolConfig () .setMaxIdle (maxIdle); factory.getPoolConfig () .setMinIdle (minIdle) Factory.getPoolConfig () .setMaxTotal (maxActive); factory.getPoolConfig () .setMaxWaitMillis (maxWait); return factory;} @ RefreshScope @ Bean public CacheManager cacheManager (RedisTemplate redisTemplate) {RedisCacheManager cacheManager = new RedisCacheManager (redisTemplate); / / Number of seconds before expiration. Defaults to unlimited (0) cacheManager.setDefaultExpiration (10); / / set the key-value timeout return cacheManager;} @ RefreshScope @ Bean public RedisTemplate redisTemplate (RedisConnectionFactory factory) {StringRedisTemplate template = new StringRedisTemplate (factory); setSerializer (template); / / set the serialization tool so that ReportBean does not need to implement Serializable interface template.afterPropertiesSet (); return template @ RefreshScope private void setSerializer (StringRedisTemplate template) {Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper om = new ObjectMapper (); om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper (om); template.setValueSerializer (jackson2JsonRedisSerializer);}}

4. RedisUtils class

Import java.io.Serializable;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.HashOperations;import org.springframework.data.redis.core.ListOperations;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.SetOperations;import org.springframework.data.redis.core.ValueOperations;import org.springframework.data.redis.core.ZSetOperations;import org.springframework.stereotype.Service @ Servicepublic class RedisUtils {@ Autowired private RedisTemplate redisTemplate; / * write cache * @ param key * @ param value * @ return * / public boolean set (final String key, Object value) {boolean result = false; try {ValueOperations operations = redisTemplate.opsForValue (); operations.set (key, value); result = true } catch (Exception e) {e.printStackTrace ();} return result;} / * write cache setting aging time * @ param key * @ param value * @ return * / public boolean set (final String key, Object value, Long expireTime, TimeUnit timeUnit) {boolean result = false Try {ValueOperations operations = redisTemplate.opsForValue (); operations.set (key, value); redisTemplate.expire (key, expireTime, timeUnit); result = true;} catch (Exception e) {e.printStackTrace ();} return result } / * batch delete the corresponding value * @ param keys * / public void remove (final String... Keys) {for (String key: keys) {remove (key);}} / * bulk delete key * @ param pattern * / public void removePattern (final String pattern) {Set keys = redisTemplate.keys (pattern); if (keys.size () > 0) {redisTemplate.delete (keys) Delete the corresponding value * @ param key * / public void remove (final String key) {if (exists (key)) {redisTemplate.delete (key) }} / * determine whether there is a corresponding value * @ param key * @ return * / public boolean exists (final String key) {return redisTemplate.hasKey (key);} / * read cache * @ param key * @ return * / public Object get (final String key) {Object result = null ValueOperations operations = redisTemplate.opsForValue (); result = operations.get (key); return result;} / * * Hash add * @ param key * @ param hashKey * @ param value * / public void hmSet (String key, Object hashKey, Object value) {HashOperations hash = redisTemplate.opsForHash (); hash.put (key,hashKey,value) } / * Hash get data * @ param key * @ param hashKey * @ return * / public Object hmGet (String key, Object hashKey) {HashOperations hash = redisTemplate.opsForHash (); return hash.get (key,hashKey) } / * list add * @ param k * @ param v * / public void lPush (String kMagneObject v) {ListOperations list = redisTemplate.opsForList (); list.rightPush (kzov) } / * list get * @ param k * @ param l * @ param L1 * @ return * / public List lRange (String k, long l, long L1) {ListOperations list = redisTemplate.opsForList (); return list.range (KJE LJ L1) } / * Collection add * @ param key * @ param value * / public void add (String key,Object value) {SetOperations set = redisTemplate.opsForSet (); set.add (key,value) } / * Collection get * @ param key * @ return * / public Set setMembers (String key) {SetOperations set = redisTemplate.opsForSet (); return set.members (key) } / * * ordered collection add * @ param key * @ param value * @ param scoure * / public void zAdd (String key,Object value,double scoure) {ZSetOperations zset = redisTemplate.opsForZSet (); zset.add (key,value,scoure) } / * * ordered collections get * @ param key * @ param scoure * @ param scoure1 * @ return * / public Set rangeByScore (String key,double scoure,double scoure1) {ZSetOperations zset = redisTemplate.opsForZSet (); return zset.rangeByScore (key, scoure, scoure1);}

5. Test and modify controller

Import java.util.concurrent.TimeUnit;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.chenqi.springboot.redis.RedisUtils;import com.chenqi.springboot.service.TestService;@RestControllerpublic class SpringBootController {public static final Logger log = LoggerFactory.getLogger (SpringBootController.class); @ Autowired TestService testService @ Autowired private RedisUtils redisUtils; @ RequestMapping (value = "/ hello/ {id}") public String hello (@ PathVariable (value = "id") String id) {/ / query whether boolean hasKey = redisUtils.exists (id); String str = ""; if (hasKey) {/ / get cache Object object = redisUtils.get (id) Log.info ("data obtained from cache" + object); str = object.toString ();} else {/ / get information from database log.info ("get data from database"); str = testService.test () / / data insertion cache (parameter meaning in set: key value, user object, cache existence time 10 (long type), time unit) redisUtils.set (id,str,10L,TimeUnit.MINUTES); log.info ("data insertion cache" + str);} return str;}}

Start the project, visit http://localhost:8002/hello/111 for the first time

Through the console output, we can see that the data was obtained from the database and stored in the redis cache.

Let's refresh the browser again.

As you can see, the second time is read from the cache, let's try to refresh the browser constantly

As you can see, it is all fetched from the cache afterwards.

At this point, our redis is ready.

The above is all the content of this article "the case of integrating redis with springBoot". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to 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.

Share To

Database

Wechat

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

12
Report