Springboot整合mybatis_plus + redis(使用注解的方式)

时间:2024-04-12 08:41:25

知识点:

使用Cache注解开发:

常用注解 说明
@EnableCaching 开启缓存注解功能,通常加在启动类上
@Cacheable 在方法执行前先查询缓存中是否有数据,如果有数据,则直接返回缓存数据;如果没有缓存数据,调用方法并将方法返回值放到缓存中
@CacheEvict 从缓存中删除数据

 配置properties.yml开启Cache

spring:
  redis:
    host: localhost
    port: 6379
    password:
    database: 0
    # lettuce连接池配置
    lettuce:
      pool:
        max-active: 8
        max-wait: 10000
        max-idle: 20
        min-idle: 10
  cache:
    type: redis #开启使用redis缓存工具

在启动类上添加注解:
@EnableCaching //启用缓存

在方法执行前添加相应的注解:@Cacheable(查询) @CacheEvict(删除)

首先创建一个springboot工程(勾选一下依赖项):

 引入依赖:

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--easy-captcha 用于生成验证码-->
        <dependency>
            <groupId>com.github.whvcse</groupId>
            <artifactId>easy-captcha</artifactId>
            <version>1.6.2</version>
        </dependency>
        <!--    使用mybatis-plus的起步依赖    -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!--   使用mysql的数据库     -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--    druid连接池    -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.6</version>
        </dependency>
        <!--      使用缓存   -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

着重引入spring-boot-starter-cache依赖,因为需要使用Cache的注解:

添加实体类:

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("t_user")
public class User implements Serializable {
    private Long id ;
    private String name ;
    private String password ;
}

mapper:

public interface UserMapper  extends BaseMapper<User> {
}

service:

public interface UserService extends IService<User>{
    User findById(Integer id);

    boolean removeById(Integer id);

}
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final RedisTemplate<String, Object> redisTemplate;

    @Resource
    private UserMapper userMapper;

    @Override
    @Cacheable("user:id")
    public User findById(Integer id) {
        //查询数据库中的User对象
        User user = userMapper.selectById(id);
        System.out.println("正在从数据库中的捞取数据……");
        return user;
    }

    @Override
    @CacheEvict("user:id")
    public boolean removeById(Integer id) {
        int delete = userMapper.deleteById(id);
        //删除成功!
        if (delete != 0) {
            return true;
        }
        return false;
    }
}

controller:

@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("/find/{id}")
    public ResponseEntity<User> findById(@PathVariable Integer id) {
        User byId = userService.findById(id);
        return ResponseEntity.ok(byId);
    }

    @GetMapping("/del/{id}")
    public boolean deleteById(@PathVariable Integer id) {
        boolean remove = userService.removeById(id);
        return remove;
    }
}

配置类:

/**
 * 配置类
 */
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        //创建RedisTemplate对象
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        //设置连接工厂
        redisTemplate.setConnectionFactory(factory);
        //设置key的序列化方式
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate;
    }
}

properties.yml配置文件

spring:
  redis:
    host: localhost
    port: 6379
    password:
    database: 0
    # lettuce连接池配置
    lettuce:
      pool:
        max-active: 8
        max-wait: 10000
        max-idle: 20
        min-idle: 10
  cache:
    type: redis #开启使用redis缓存工具
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    druid:
      max-active: 10
mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: net.wanho.entity
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true
#配置服务器
server:
  port: 8088

现在进行测试:                                                                                       redis:显示的数据

数据库日志文件: 

 

当再次查询数据id为1的数据:控制台不再输出 (因为redis中已经存在id=1的数据)

查询id=3的数据:                                                                                      已经在redis中记录下来:

 

删除操作:                                                                        查看redis数据: