SoFunction
Updated on 2025-04-13

SpringBoot + Mybatis Plus Detailed steps to integrate Redis

Typical application scenarios of Redis in user management systems

Combining the interfaces for adding, deleting, modifying and checking of your users, the following are the practical scenarios and specific implementation solutions of Redis:

Scene effect Implementation plan
User information cache Reduce database pressure and speed up query response useSpring Cache + RedisAnnotation cache
Log in token storage Distributed Session or JWT Token Management Bind the token with user information and set the expiration time
Interface current limit Prevent malicious interface flash Implement sliding window current limit based on Redis counter
Repeated submission interception Prevent users from submitting forms repeatedly Use Redis to store request unique identifiers and set short-term expiration
Hotspot data preload Cache high-frequency access data in advance Timing Tasks + Redis Storage

Detailed steps to install Redis on Mac M1

1. Install Redis via Homebrew

# Install Homebrew (if not already installed)/bin/bash -c "$(curl -fsSL /Homebrew/install/HEAD/)"
# Install Redisbrew install redis

2. Start Redis Service

# Foreground start (for test, Ctrl+C exit)redis-server
#Background startup (recommended)brew services start redis

3. Verify the installation

# Connect to Redis Clientredis-cli ping  # Should return "PONG"

Spring Boot 3 Integration Redis

1. Add dependencies

existmiddle:

		<!-- Spring Cache Core dependencies -->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <!-- Redis drive -->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId></groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

2. Configure Redis connection

spring:
  data:
    redis:
      host: localhost
      port: 6379
      # password: your-password # If password is set      lettuce:
        pool:
          max-active: 8
          max-idle: 8

3. Example

Configuration class

package .spring_demo01.config;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .*;
import ;
@Configuration
public class RedisConfig {
    // Configure RedisTemplate    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        (factory);
        // Key serialization        (new StringRedisSerializer());
        // Value is serialized to JSON        (new GenericJackson2JsonRedisSerializer());
        // Hash structure serialization        (new StringRedisSerializer());
        (new GenericJackson2JsonRedisSerializer());
        return template;
    }
    // Configure cache manager    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = ()
                .serializeKeysWith((new StringRedisSerializer()))
                .serializeValuesWith((new GenericJackson2JsonRedisSerializer()))
                .entryTtl((30)); // Set the default expiration time        return (factory)
                .cacheDefaults(config)
                .build();
    }
}

Interface current limiting tool class

package .spring_demo01.utils;
import ;
import ;
import ;
import ;
import ;
@Component
public class RateLimiter {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    public boolean allowRequest(String userId) {
        String key = "rate_limit:" + userId;
        long now = ();
        long windowMs = 60_000; // 1 minute        // Remove request records outside the window        ().removeRangeByScore(key, 0, now - windowMs);
        // Statistics the number of requests in the current window        Long count = ().zCard(key);
        if (count != null && count >= 10) {
            return false; // Exceed the limit        }
        // Record this request        ().add(key, ().toString(), now);
        (key, windowMs, );
        return true;
    }
}

Entity Class

package .spring_demo01.entity;
import .*;
import ;
import ;
import ;
@Data
@TableName("user")
@JsonIgnoreProperties(ignoreUnknown = true) // Prevent JSON deserialization problemspublic class User implements Serializable { // Implement Serializable    @TableId(type = ) // The primary key is increased by itself    private Long id;
    private String name;
    private Integer age;
    private String email;
}

Service layer

package .spring_demo01.;
import ;
import .spring_demo01.;
import .spring_demo01.;
import .spring_demo01.;
import ;
import ;
import ;
import ;
@Service
public class UserServiceImpl
        extends ServiceImpl<UserMapper, User>
        implements UserService {
    // Add cache to the getById method of MyBatis Plus    @Cacheable(value = "user", key = "#id")
    @Override
    public User getById(Serializable id) {
        return (id);
    }
    // Clear cache during update    @CacheEvict(value = "user", key = "#")
    @Override
    public boolean updateById(User entity) {
        return (entity);
    }
    // Clear cache when deletion    @CacheEvict(value = "user", key = "#id")
    @Override
    public boolean removeById(Serializable id) {
        return (id);
    }
}

Controller layer

package .spring_demo01.controller;
import ;
import ;
import .spring_demo01.;
import .spring_demo01.;
import .spring_demo01.;
import .spring_demo01.;
import .slf4j.Slf4j;
import ;
import ;
import .*;
import ;
import ;
import ;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private RateLimiter rateLimiter;
    // ------------------------------------------------------------------------------------------------------------------------------    @PostMapping
    public String addUser(@RequestBody User user, @RequestHeader String clientId) {
        String key = "SUBMIT_LOCK:" + clientId + ":" + ();
        // Repeated submissions are not allowed within 10 seconds        Boolean success = ()
                .setIfAbsent(key, "", (10));
        if ((success)) {
            throw new RuntimeException("Do not repeat submission");
        }
        (user);
        return "Newly added";
    }
    // ------------------------------------------------------------------------------------------------------------------------------    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        (id);
        return "Delete successfully";
    }
    @DeleteMapping("/batch")
    public String deleteBatch(@RequestBody List<Long> ids) {
        (ids);
        return "Batch deletion succeeded";
    }
    // ------------------------------ change ------------------------------    @PutMapping
    public String updateUser(@RequestBody User user) {
        (user);
        return "Update Successfully";
    }
    // ------------------------------ check ------------------------------    @GetMapping("/{id}")
    @AdminOnly
    public User getUserById(@PathVariable Long id) {
        return (id);
    }
    @GetMapping("/list")
    public List<User> listUsers(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer age) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (name != null) {
            ("name", name); // Fuzzy query name        }
        if (age != null) {
            ("age", age);     // Accurate age query        }
        return (wrapper);
    }
    @GetMapping("/page")
    public Page<User> pageUsers(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestHeader(value = "Authorization") String token) {
        // Get user ID from the token        ("token:{}", token);
        ("User:{}", ().get((" ")[1]));
        User user = (User) ().get((" ")[1]);
        if (user == null) throw new RuntimeException("Not logged in");
        // Current limit verification        if (!("PAGE_" + ())) {
            throw new RuntimeException("Requests too frequently");
        }
        return (new Page<>(pageNum, pageSize));
    }
    // ------------------------------ other ------------------------------
    @GetMapping("/error")
    public String getError() {
        throw new RuntimeException();
    }
    @PostMapping("/login")
    public String login(@RequestBody User user) {
        ("login user:{}", user);
        // Verify user logic (simplified example)        User dbUser = (new QueryWrapper<User>()
                .eq("id", ())
                .eq("name", ()));
        if (dbUser == null) {
            throw new RuntimeException("Login failed");
        }
        // Generate tokens and store        String token = "TOKEN_" + ();
        ().set(
                token,
                dbUser,
                (30)
        );
        return token;
    }
}

Add annotations to the startup class:

package .spring_demo01;
import ;
import ;
import ;
import ;
import ;
@SpringBootApplication
@MapperScan(".spring_demo01.mapper")
@ServletComponentScan // Enable Servlet component scanning (such as Filter, Servlet)@EnableCaching // Start cache, use Redispublic class SpringDemo01Application {
    public static void main(String[] args) {
        (, args);
    }
}

Frequently Asked Questions

Q1: Connection Redis timeout

  • Check service status: Runredis-cli pingConfirm whether Redis is operating normally
  • View port occupancylsof -i :6379
  • Turn off the firewallsudo ufw allow 6379

Q2: Spring Boot cannot inject RedisTemplate

  • Confirm the configuration class:Add to@EnableCachingand@Configuration
  • Check the serializer: Explicitly configure serialization to avoid ClassCastException
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        (factory);
        (new StringRedisSerializer());
        (new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

Summarize

With Redis you can quickly implement it for your project:

  • High-performance cache layer- Reduce database load
  • Distributed Session Management- Support horizontal scaling
  • Fine flow control- Ensure system stability

This is the end of this article about the detailed steps of integrating SpringBoot + Mybatis Plus Redis. For more related SpringBoot Mybatis Plus Redis content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!