Redis实现投票功能

一、背景介绍

投票功能是一个非常常见的Web应用场景,SpringBoot作为当今流行的Web开发框架,为了提高开发效率和性能,通常需要整合一些第三方组件。Redis是一种高性能的键值对存储数据库,而Mybatis-plus则是Mybatis的扩展版本,提供了更强大和便捷的数据库操作方式。本文将介绍如何将Redis和Mybatis-plus整合到SpringBoot中,实现投票功能。

二、开发环境

  • JDK 1.8
  • SpringBoot 2.5.0
  • Redis 6.2.4
  • Mybatis-plus 3.4.3
  • IntelliJ IDEA

三、技术实现

1. 配置Redis

在SpringBoot的配置文件application.yml中添加Redis的配置:

spring:
  # Redis相关配置
  redis:
    # Redis服务器IP地址
    host: localhost
    # Redis服务器端口号
    port: 6379
    # Redis服务器密码
    password: 
    # Redis连接池最大连接数
    jedis:
      pool:
        max-active: 8
    # Redis连接池最大等待时间(单位:毫秒)
    lettuce:
      pool:
        max-wait: -1ms
    timeout: 5000ms

2. 配置Mybatis-plus

在SpringBoot的配置类中添加Mybatis-plus的配置:

@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {
    
    

    /**
     * Mybatis-plus分页插件配置
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
    
    
        return new PaginationInterceptor();
    }

    /**
     * Mybatis-plus通用Mapper配置
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
    
    
        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
        scannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        scannerConfigurer.setBasePackage("com.example.mapper");
        return scannerConfigurer;
    }
}

3. 实现投票功能

首先创建一个投票的实体类Vote,包含投票项的id和投票数count:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Vote implements Serializable {
    
    
    private Long id;
    private Integer count;
}

然后创建投票的数据库表vote,包含两个字段id和count,id为主键:

CREATE TABLE `vote` (
  `id` bigint(20) NOT NULL,
  `count` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

接着创建投票的Mapper接口VoteMapper和对应的XML文件VoteMapper.xml,定义增加投票数和查询投票数的方法:

public interface VoteMapper extends BaseMapper<Vote> {
    
    
    /**
     * 增加投票数
     * @param id 投票项id
     * @return
     */
    int increaseCount(@Param("id") Long id);

    /**
     * 查询投票数
     * @param id 投票项id
     * @return
     */
    int selectCount(@Param("id") Long id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.VoteMapper">

    <!-- 增加投票数 -->
    <update id="increaseCount">
        update vote set count = count + 1
        where id = #{id}
    </update>

    <!-- 查询投票数 -->
    <select id="selectCount" resultType="int">
        select count
        from vote
        where id = #{id}
    </select>

</mapper>

接下来创建投票的Service类VoteService,其中增加投票数和查询投票数的方法使用了Redis缓存:

@Service
public class VoteService {
    
    

    @Autowired
    private VoteMapper voteMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     ** @param id 投票项id
     */
    public void increaseCount(Long id) {
    
    
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        String key = "vote:" + id;
        // 先从缓存中获取投票数
        Integer count = (Integer) operations.get(key);
        // 如果缓存中没有,则从数据库中获取,并存入缓存
        if (count == null) {
    
    
            count = voteMapper.selectCount(id);
            if (count != null) {
    
    
                operations.set(key, count);
            }
        }
        // 如果缓存中有,则增加投票数并更新缓存
        if (count != null) {
    
    
            operations.increment(key);
            voteMapper.increaseCount(id);
        }
    }

    /**
     * 查询投票数
     * @param id 投票项id
     * @return
     */
    public Integer selectCount(Long id) {
    
    
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        String key = "vote:" + id;
        // 先从缓存中获取投票数
        Integer count = (Integer) operations.get(key);
        // 如果缓存中没有,则从数据库中获取,并存入缓存
        if (count == null) {
    
    
            count = voteMapper.selectCount(id);
            if (count != null) {
    
    
                operations.set(key, count);
            }
        }
        return count;
    }
}

最后创建投票的Controller类VoteController,提供增加投票数和查询投票数的接口:

@RestController
public class VoteController {
    
    

    @Autowired
    private VoteService voteService;

    /**
     * 增加投票数接口
     * @param id 投票项id
     * @return
     */
    @PostMapping("/vote/increase")
    public String increaseCount(@RequestParam Long id) {
    
    
        voteService.increaseCount(id);
        return "success";
    }

    /**
     * 查询投票数接口
     * @param id 投票项id
     * @return
     */
    @GetMapping("/vote/select")
    public Integer selectCount(@RequestParam Long id) {
    
    
        Integer count = voteService.selectCount(id);
        return count == null ? 0 : count;
    }
}

四、测试运行

启动SpringBoot应用后,在浏览器中访问http://localhost:8080/vote/select?id=1,可以查询id为1的投票项的投票数;再访问http://localhost:8080/vote/increase?id=1,可以对id为1的投票项进行投票。同时可以在Redis客户端中查看投票项的投票数是否正确。

五、总结

本文介绍了如何将Redis和Mybatis-plus整合到SpringBoot中,以实现投票功能。其中Redis缓存可以增加应用性能,Mybatis-plus可以简化数据库操作。代码已上传至Github:https://github.com/chatbot-ai/spring-boot-redis-mybatis-vote。

猜你喜欢

转载自blog.csdn.net/weixin_65950231/article/details/130948712