RedisTemplate of Spring boot integration redis method

Using Spring boot to integrate redis, its essence is to use Spring's Spring Data Redis to process the implementation. Before using it, ensure that the redis installation is complete and start its server, and then you need to add the corresponding dependencies of redis and redis connection pool in spring boot in the framework, and then write the corresponding configuration file, write a simple demo, you can directly call the spring provided RedisTemplate is used to implement simple crud operations. Note that object storage needs to be serialized and cannot be stored directly. The Serializable class can be implemented in the object class.
1. Add dependency
Open a spring boot project, there are two very important dependencies here, one is the redis dependency in spring boot, and the other is the dependency required by the redis connection pool

	<!-- redis依赖包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

Second, write the configuration file.
Here is mainly to configure the basic configuration of redis and the configuration of connection pool properties

spring:
  #redis
  redis:
    host: 127.0.0.1
    port: 6379
    database: 0
    timeout: 5000
    #连接池
    jedis:
      pool:
        max-idle: 20
        min-idle: 2
        max-wait: 3000
        max-active: 50

3. Write a small demo to
add an object to redis, with the key being String and the value being the object.
The redisTemplate provided by spring has already encapsulated some things, and you can directly call and use the simple redis CRUD operation. Generally speaking, this class will be made into a tool class to facilitate the use of the service layer.

package com.example.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.logging.Logger;

@Component
public class RedisUtils {
    
    

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    Logger log = Logger.getLogger("RedisUtils.class");
    /**
     * 读取缓存
     */
    public Object get(final Object key) {
    
    
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 写入缓存
     */
    public boolean set(final Object key, Object value) {
    
    
        boolean result = false;
        try {
    
    
            redisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 更新缓存
     */
    public boolean getAndSet(final Object key, Object value) {
    
    
        boolean result = false;
        try {
    
    
            redisTemplate.opsForValue().getAndSet(key, value);
            result = true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除缓存
     */
    public boolean delete(final Object key) {
    
    
        boolean result = false;
        try {
    
    
            redisTemplate.delete(key);
            result = true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return result;
    }

}

Write the object class and serialize it (because to store in redis to the content, the object must be serialized before it can be stored). Serialization will be serialized when stored, and deserialized when taken out!

package com.example.model;
import lombok.Data;
import java.io.Serializable;
/*
* 对象存储到redis中需要先序列化
* */
@Data
public class User1 implements Serializable {
    
    
    private int id;
    private String name;
    private int age;
}

In the service layer, write the implementation directly, not the interface

package com.example.serviceimpl;
import com.example.model.User1;
import com.example.util.RedisUtils;
import com.example.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RedisServiceimpl implements RedisService {
    
    

    @Autowired
    private RedisUtils redisUtils;
    public void setUser(){
    
    
        User1 u = new User1();
        u.setAge(1);
        u.setId(1);
        u.setName("tom");
        redisUtils.set("user001",u);
    }
    public Object getByKey(){
    
    
        return redisUtils.get("user001");
    }
}

Controller layer call

package com.example.controller;

import com.example.model.User;
import com.example.model.User1;
import com.example.service.RedisService;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;
import java.util.logging.Logger;

@Controller
public class HelloController {
    
    

    Logger log = Logger.getLogger("HelloController.class");
    @Autowired
    UserService userService;
    @Autowired
    RedisService redisService;

    @GetMapping(value = "/hello")
    public String hello(){
    
    
        redisService.setUser();
        User1 u = (User1) redisService.getByKey();
        log.info(String.valueOf(u));
        return "hello";
    }
}

Running results
Insert picture description here
This is just the simplest demo. The serialization operations inside and the five data types supported by redis are all in the process of learning.

Guess you like

Origin blog.csdn.net/Wangdiankun/article/details/106055414