SpringBoot整合Redis

原创
2020/05/21 18:15
阅读数 127

SpringBoot整合Redis

Redis在项目中的应用非常多,应用场景也非常多,所以在Springboot中整合Redis是一个非常必要的事情,本文简单介绍如何集成Redis,并且简单运用相关API对Redis进行操作。

SpringBoot整合Redis

一、依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
	<!-- 版本跟随Springboot就可以 -->
</dependency>

二、application.yml配置文件

server:
  port: 8081

spring:
  application:
    name: springboot-redis
  redis:
    host: 127.0.0.1
    port: 6379
    database: 0

三、先配置基本类

/**
 * <p>
 *     系统用户,这里使用lombok的@Data,不知道的同学请自行研究
 * </p>
 *
 * @author Calvin
 * @date 2020/05/21
 * @since
 */
@Data
public class SysUser {

    /**
     * ID
     */
    private String id;

    /**
     * 账户名
     */
    private String account;

    /**
     * 邮箱
     */
    private String email;

    /**
     * 手机号
     */
    private String telephone;

    /**
     * 密码
     */
    private String password;

    /**
     * 最后登录时间
     */
    private Date lastLogin;

    /**
     * 用户创建时间
     */
    private Date createTime;

    /**
     * 最后修改时间
     */
    private Date lastModifyTime;

}

四、配置BeanUtilsHashMapper使其能进行转换,配置Redis自增序列

**
 * <p> </p>
 *
 * @author Calvin
 * @date 2020/05/21
 * @since
 */
public class SysUserRedisConfig {

    /**
     * SysUser自增序列的
     * @return
     */
    private static final String SYS_USER_ID = "sys_user_id";

    @Autowired
    private StringRedisTemplate template;

	/**
    * 能够进行Bean和Map的转换
	* @return
    */
    @Bean
    public BeanUtilsHashMapper<SysUser> sysUserBeanUtilsHashMapper(){
        return new BeanUtilsHashMapper<>(SysUser.class);
    }

    /**
     * 配置针对sysUser的自增序列
     * @return
     */
    @Bean(name = "sysUserAtomicLong")
    public RedisAtomicLong getRedisAtomicLong() {
        RedisAtomicLong counter = new RedisAtomicLong(SYS_USER_ID, template.getConnectionFactory());
        return counter;
    }
}

五、编写DAO

/**
 * <p>
 *     sysUserDao
 * </p>
 *
 * @author Calvin
 * @date 2020/05/21
 * @since
 */
@Component
public class SysUserRedisDao {

    private static final Logger logger = LoggerFactory.getLogger(SysUserRedisDao.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource(name = "sysUserAtomicLong")
    private RedisAtomicLong redisAtomicLong;

    @Resource
    private BeanUtilsHashMapper<SysUser> beanUtilsHashMapper;


    /**
     * key,用::双冒号隔开,符合规约
     */
    private static final String sysUserRedisKey = "SysUser::";


    /**
     * 增加一个用户
     * @param sysUser
     * @return
     */
    public SysUser addUser(SysUser sysUser){
        Long id = getRedisSequence();
        String key = sysUserRedisKey + id;
        sysUser.setId(id);
        Map<String, String> userValueMap = beanUtilsHashMapper.toHash(sysUser);
        stringRedisTemplate.opsForHash().putAll(key, userValueMap);
        return sysUser;
    }


    /**
     * 更新
     * @param sysUser
     * @return
     */
    public boolean updateUser(SysUser sysUser){
        Long id = sysUser.getId();
        //加锁
        Boolean lock = stringRedisTemplate.opsForValue()
                .setIfAbsent(sysUserRedisKey + "::lock" + id, "1");
        if(lock == Boolean.TRUE){
            Map<String, String> userValueMap = beanUtilsHashMapper.toHash(sysUser);
            stringRedisTemplate.opsForHash().putAll(sysUserRedisKey + id, userValueMap);
            //关闭锁
            stringRedisTemplate.delete(sysUserRedisKey + "::lock" + id);
            return true;
        }else{
            return false;
        }
    }



    /**
     * <p>
     *     查询所有的实现, 其实此处应该用list类型去实现,排序要用zset实现,但是限于篇幅,
     *     所以只针对Hash类型的api做简单介绍,旨在实验集成Redis是否好使
     * </p>
     * @param page
     * @param pageSize
     * @return
     */
    public List<SysUser> listAll(int page, int pageSize) {
        Set<Object> keys = stringRedisTemplate.opsForHash().keys(sysUserRedisKey + "*");
        List<SysUser> result = new ArrayList<>();
        HashOperations<String, String, String> operations = stringRedisTemplate.opsForHash();
        for (Object key : keys) {
            Map<String, String> entries = operations.entries(String.valueOf(key));
            SysUser sysUser = beanUtilsHashMapper.fromHash(entries);
            result.add(sysUser);
        }
        int fromIndex = page*pageSize;
        if(result.size() > fromIndex){
            return result.subList(fromIndex, fromIndex+pageSize);
        }
        return null;
    }


    /**
     * 获取自增序列
     * @return
     */
    private long getRedisSequence() {
        long sequence = 0L;
        try {
            if (redisAtomicLong.get() == 0) {
                redisAtomicLong.getAndSet(0L);
            }
            sequence = redisAtomicLong.incrementAndGet();
        } catch (Exception ex) {
            logger.error("Failed to get sequence.", ex);
        }
        return sequence;
    }
}

六、接口

/**
 * <p> </p>
 *
 * @author Calvin
 * @date 2020/05/21
 * @since
 */
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private SysUserRedisDao sysUserRedisDao;


    /**
     * 新增用户
     * @param account
     * @param email
     * @param telephone
     * @param password
     * @return
     */
    @GetMapping("/add")
    public ResultEntity add(String account, String email, String telephone, String password){
        SysUser sysUser = new SysUser();
        sysUser.setAccount(account);
        sysUser.setEmail(email);
        sysUser.setTelephone(telephone);
        sysUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        sysUser = sysUserRedisDao.addUser(sysUser);
        return ResultEntityBuilder.buildSuccess(sysUser);
    }

    /**
     * 更新用户信息
     * @param sysUser
     * @return
     */
    @GetMapping("/update")
    public ResultEntity update(SysUser sysUser){
        boolean b = sysUserRedisDao.updateUser(sysUser);
        if(b){
            return ResultEntityBuilder.buildSuccess("success");
        }else{
            return ResultEntityBuilder.buildError(401,"该用户暂时锁定,请稍后重试");
        }

    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public ResultEntity listAllUser(int page, int pageSize){
        List<SysUser> sysUserList = sysUserRedisDao.listAll(page, pageSize);
        return ResultEntityBuilder.buildSuccess(sysUserList);
    }
}

七、总结

  1. 简单整合Redis,应用相关API
  2. 由于本人暂时项目中应用尚欠,有不好的地方希望高人多多指导
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部