Sringboot整合mybatis-plus+Redis

1.Mybatis自动生成代码
Windows下安装Redis
2.导入Redis相关依赖

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

3.编写application.yml文件

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/redis?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 1041370063
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password: 123456
    timeout: 2000s
    lettuce:
      pool:
        max-wait: 60s
        max-idle: 10
        min-idle: 10
        max-activ: 8
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

4.编写RedisConfig配置类

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        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);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

5.编写一个类,将MySQL数据库的数据添加到Redis缓存

@SpringBootTest
public class MySqlToRedis {
    @Autowired
    PeopleService peopleService;

    @Resource
    private RedisTemplate redisTemplate;
    private static final String ALL_USER="ALL_USER_LIST";
    @Test
    public void Initialized(){
        //查询数据库所有的用户
        List<People> peopleList=peopleService.list();
        //清除缓存中的用户数据
        redisTemplate.delete(ALL_USER);
        //将数据放到Redis缓存之中
        redisTemplate.opsForList().leftPushAll(ALL_USER,peopleList);

    }
}

6.启动测试类,打开RDM可以查看到数据库的数据已存在于缓存中
在这里插入图片描述

在这里插入图片描述
7.Redis+MybatisPlus的增删查改

  • 7.1 mapper层:

    在PeopleMapper.java类添加注解@Repository

  • 7.2 service.impl层:重写mybatis-plus相关方法

@Service
@Slf4j
public class PeopleServiceImpl extends ServiceImpl<PeopleMapper, People> implements PeopleService {
    @Autowired
    private RedisTemplate redisTemplate;
    private static final String ALL_USER="ALL_USER_LIST";
    @Autowired
    PeopleMapper peopleMapper;

    /*
    * 获取用户
    * */
    @Override
    public People getById(Serializable id) {
        //查询Redis缓存中的所有数据
        List<People> peopleList=redisTemplate.opsForList().range(ALL_USER,0,-1);
        if (peopleList!=null&&peopleList.size()>0) {
            for (People people : peopleList) {
                if (String.valueOf(people.getId()).equals(id)) {
                    log.info("Redis");
                    return people;
                }
            }
        }
        //查询数据库中的数据
        People people=peopleMapper.selectById(id);
        if(people!=null){
            //将数据插入Redis缓存之中
            redisTemplate.opsForList().leftPush(ALL_USER,people);
        }
        log.info("MySQL");
        return people;
    }

    /*
    * 删除用户
    * */
    @Override
    public boolean removeById(Serializable id) {
        //先删除数据库用户
        People people=peopleMapper.selectById(id);
        int result=peopleMapper.deleteById(id);
        //删除缓存
        if(result!=0){
            redisTemplate.opsForList().remove(ALL_USER,0,people);
            log.info("Redis");
            return true;
        }
        return false;
    }

    /*
    * 更新用户
    * */

    @Override
    public boolean updateById(People newPeople) {
        //更新数据库
        People people=peopleMapper.selectById(newPeople.getId());
        int result=peopleMapper.updateById(newPeople);
        if (result!=0){
            //先删除原来的缓存
            redisTemplate.opsForList().remove(ALL_USER,0,people);
            //将更新的用户加入缓存
            redisTemplate.opsForList().leftPush(ALL_USER,newPeople);
            return true;
        }
        return false;
    }
}

  • 7.3 controller层
@RestController
public class PeopleController {
    @Autowired
    PeopleService peopleService;
    @GetMapping("/all")
    public List<People> getAllPeople(){
        return peopleService.list();
    }
    @GetMapping("/get/{id}")
    public People getPeople(@PathVariable Serializable id){
        return peopleService.getById(id);
    }
    @GetMapping("/delete/{id}")
    public boolean deletePeople(@PathVariable Serializable id){
        return peopleService.removeById(id);
    }
    @GetMapping("/update")
    public boolean updatePeople(){
        People people=new People();
        people.setId(1);
        people.setName("小末");
        people.setGender("女");
        return peopleService.updateById(people);
    }
}

项目实例

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒙面侠1024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值