One article to learn the use of redis in springBoot

"Collection never stops, practice never starts", maybe there are some good questions and methods, but after being selected by you for collection, you forget to collect dust in the favorites? Please be sure to open your heavy collection to review today, and share those good things that made you wow!

 

 

1. What is redis cache

Redis Cache is an open-source, log-type, Key-Value database that is written in ANSIC language, supports network, can be memory-based or persistent, and provides APIs in multiple languages.

Second, the advantages and disadvantages of redis cache

advantage:

  1. High performance: Redis memory management is very efficient, very fast, and can take advantage of multiple cores. In scenarios with high access speed requirements, using Redis cache can significantly improve system performance and reduce the pressure on the backend system.
  2. Wide range of support: Redis supports multiple data types and data structures, such as lists, hash tables, sets, ordered sets, etc., which can meet diverse caching requirements.
  3. High reliability: Redis supports data persistence and redundant backup to ensure data reliability and high availability.
  4. Scalability: Redis supports cluster mode, which can easily expand cache capacity and load balancing to meet systems of different scales and needs.
  5. Ease of use: Redis's API is easy to use, with rich documentation and community resources, allowing developers to quickly get started and master it.

In a word:

The response speed is accelerated, the read operations on the database are reduced, and the pressure on the database is reduced.

shortcoming:

  1. Need to occupy memory: the data cached by Redis is stored in memory, which requires a certain amount of memory resources. If there is too much cached data, it will cause insufficient memory and affect system performance.
  2. Loss of data persistence: Redis supports data persistence, but in some cases, data persistence will cause a certain loss in performance. For example, performing RDB persistence operations under high concurrency conditions will block the IO operations of the Redis server , affecting system performance.
  3. Reliability issues: Redis's master-slave architecture and high availability mechanism can guarantee system reliability, but there are still certain risks in the event of node failures and network abnormalities.
  4. Consistency issues: Redis's cache is strongly consistent, which may not be suitable for use in some scenarios. Such as distributed locks, distributed transactions, etc., need to ensure the weak consistency of the system.
  5. Security issues: The security of Redis needs to be configured and reinforced by developers. If it is not configured correctly, it may face security risks such as information leakage.

In a word:

  • The data is stored in the memory, and the data will be lost if the host is powered off
  • Storage capacity is limited by physical memory and can only be used for high-performance operations with small data volumes
  • It is difficult to expand capacity online, and you must ensure that there is enough space when the system goes online
  • When used for caching, it is prone to problems such as 'cache avalanche' and 'cache breakdown'

3. Why use redis cache

  1. Redis can use dozens of gigabytes of memory for caching, and the speed is fast
  2. Redis cache can be persisted, which is convenient for data backup and recovery;
  3. Redis supports simple transactions, and operations satisfy atomicity
  4. Redis can implement distributed caching;
  5. Redis can handle millions of concurrency per second and is a professional caching service;
  6. Redis cache has an expiration mechanism;
  7. Redis has a rich API and is easy to use;
  8. Support sentinel mechanism to realize automatic failover;

Using redis as a cache can reduce the pressure on the database, especially when a large amount of data needs to be queried frequently. Using redis can also improve access speed, because redis data will be stored in memory.

4. Data types supported by redis

String (string)
hash table (hash)
list (list)
set (set)
ordered set (zset)
To ensure read efficiency, Redis stores data objects in memory and supports periodic writing of updated data into a disk file. And it also provides intersection and union, and some operations that are sorted in different ways.

The characteristics of redis determine its function, and it can be used to do the following things!

Leaderboard, using zset can easily realize the sorting function.
Counter, using the atomic self-increment operation in redis, can count the number of readings, likes and other functions.
Simple message queue, list storage structure, to meet the principle of first in first out, you can Use lpush/rpop or rpush/lpop to implement simple message queue
session sharing. In a distributed system, redis can be used to implement session sharing. The distributed solution Spring Session officially provided by spring is implemented using redis.

5. springboot integrates redis

1. Introduce dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. Add the annotation @EnableCaching to the springboot startup class to enable the caching function, as follows:

/**
  *服务启动类
  
  */
@SpringBootApplication(scanBasePackages = {"cn.xxx.common.redis","cn.xxx.task.*"})
@EnableEurekaClient
@EnableApolloConfig
@EnableFeignClients
@EnableDiscoveryClient
@EnableTransactionManagement 
@MapperScan("cn.xxx.task.dao")
@EnableScheduling
@Transactional
@EnableCaching
public class TaskApplication {

	public static void main(String[] args) {
		SpringApplication.run(TaskApplication.class,args);
	}

	/**
	 * 替换原生Decoder解析器,支持text/plain
	 * @return
	 */
	@Bean
	public Decoder feignDecoder(){
		WxMessageConverter wxConverter = new WxMessageConverter();
		ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(wxConverter);
		return new SpringDecoder(objectFactory);
	}

}


 3. Configure redis connection information

spring:
  redis:
    # redis库
    database: 0
    # redis 服务器地址
    host: localhost
    # redis 端口号
    port: 6379
    # redis 密码
    password:
    # 连接超时时间(毫秒)
    timeout: 1000
    lettuce:
      pool:
        # 连接池最大链接数(负数表示没有限制)
        max-active: 8
        # 连接池最大阻塞等待时间(负数表示没有限制)
        max-wait: -1
        # 连接池最大空闲连接数
        max-idle: 8
        # 连接池最小空闲连接数
        min-idle: 0

6. Using annotations to use redis cache (key content)

1. Annotation
@CacheConfig: Generally configured on the class, specify the cache name, which is consistent with the cache name in the above "set cache manager".
@Cacheable: It is used to cache the return result of the method. If the cache already exists, it will be obtained directly from the cache. The key of the cache can be specified from the input parameter, and the value of the cache is the return value of the method.
@CachePut: Regardless of whether the cache exists or not, the cache will be re-added every time. The key of the cache can be specified from the input parameter, and the value of the cache is the return value of the method, which is often used for updating.
@CacheEvict: Used to clear the cache
@Caching: Used to set multiple caches at once.
2. Commonly used annotation configuration parameter
value: The name of the cache configured in the cache manager, which can be understood as the concept of a group. There can be multiple sets of cache configurations in the cache manager, and each set has a name, similar to the group name. This can configure this value, choose which cache name to use, and the configuration corresponding to that cache name will be applied after configuration.
key: The key of the cache, which can be empty. If it is specified, it should be written according to the SpEL expression. If not specified, it will be combined according to all parameters of the method by default.
condition: The condition of the cache, which can be empty, written in SpEL, returns true or false, and caches only when it is true.
unless: The condition of not caching, like condition, is also written in SpEL, returns true or false, and does not cache when it is true.
3. Automatic caching
@Cacheable can be marked on a method or a class. When marked on a method, it means that the method supports caching. When marked on a class, it means that all methods of this class support caching.

If the @Cacheable annotation is added, the value will be stored in redis after the method is called, and the value will be returned directly from redis when it is called next time.
 

@Service
@CacheConfig(cacheNames = "user")
public class UserService {

    @Autowired
    private UserMapper userMapper;
    
    // 获取全部用户
    @Cacheable(key = "'allUsers'", unless = "#result==null")
    public List<Courses> findAll() {
        return userMapper.allUsers();
    }
}

   /**
     * 登录用户信息缓存(部分,脱敏处理)
     * @param mUser
     * @return
     */
    @CachePut(value = "member", key = "'userinfo:' + #mUser.userId")
    public Map<String, Object> loginUserInfo(MUser mUser) {
        // 手机号加*处理
        String starPhone = PhoneUtil.star(mUser.getPhone());
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("purePhoneNumber", starPhone);
        resMap.put("nickName", mUser.getUserName());
        resMap.put("avatarUrl", mUser.getHeadIcon());
        resMap.put("countryCode", mUser.getCountryCode());
        // resMap.put("resToken", resToken);
        resMap.put("wxAccount", mUser.getWxAccount());
        resMap.put("sex", mUser.getSex());
        resMap.put("sexName", mUser.getSexName());
        resMap.put("userState", mUser.getUserState());
        resMap.put("userStateName", mUser.getUserStateName());
        resMap.put("channelId", mUser.getChannelId());
        resMap.put("channelName", mUser.getChannelName());
        return resMap;
    }
    
    /**
     * 内部员工缓存信息
     * @param phone
     * @param status
     * @param b
     * @param messge
     * @return
     */
    @CachePut(value = "member#PT5M", key = "'employee:' + #phone")
    public Map<String, Object> employee(String phone,String status , boolean b ,String messge ) {
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("phone", phone);
        resMap.put("status", status); 
        resMap.put("flag",  b);
		resMap.put("messge",messge);
        return resMap;
    }
    
    /**
     * 是否是内部员工缓存
     * @param phone
     * @return
     */
    @Cacheable(value = "member", key = "'employee:' + #phone")
    public Map<String, Object> getEmployee(String phone) {
        return  null;
    }

Guess you like

Origin blog.csdn.net/dongjing991/article/details/131917434