Redis实现微博用户注册&;发送微博

微博用户注册

整个的流程是:
1:首先注册用户填写用户信息,先写入到db中
2:然后在存储数据到redis的hash结构中 key=”reg:user:id”

package com.kuangstudy.controller.reg;
import com.kuangstudy.entity.User;
import com.kuangstudy.service.UserService;
import com.kuangstudy.vo.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.reflect.generics.visitor.Reifier;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * @description:
 * @author: xuke
 * @time: 2021/5/22 20:05
 */
@RestController
public class RegController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("reguser")
    @ApiOperation("用户注册")
    public R regUser(User user) {
        // 1: 先把用户注册到DB中
        userService.saveOrUpdate(user);
        // 2: 然后查询最新的用户信息放入到redis的hash重
        User user1 = userService.getById(user.getId());
        Map map = R.beanToMap(user1);
        // 3: 准备用存入的key,将用户信息存入到redis的hash中
        String key = "reg:user:" + user.getId();
        redisTemplate.opsForHash().putAll(key, map);
        // 4: 设置key的失效时间一个月
        redisTemplate.expire(key, 30, TimeUnit.DAYS);
        return R.ok();
    }
}

微博发送

Redis实现微博用户注册&;发送微博_第1张图片

package com.kuangstudy.service.list;
import com.kuangstudy.entity.Content;
import com.kuangstudy.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.MapFactoryBean;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * @description:
 * @author: xuke
 * @time: 2021/6/11 23:37
 */
@Service
@Slf4j
public class PushContentService {
    @Autowired
    private RedisTemplate redisTemplate;
    public Content saveContent(Content content) {
        // 1: 保存内容到db中
        // 2: 把保存的内容写入到hash中
        Map stringObjectMap = null;
        try {
            stringObjectMap = ObjectUtils.objectToMap(content);
            String key = "weibo:content:" + content.getId();
            // 3: 把微博的内容保存到hash中
            HashOperations opsForHash = redisTemplate.opsForHash();
            opsForHash.putAll(key, stringObjectMap);
            // 4: 设置微博的有效期是30天过期
            this.redisTemplate.expire(key, 30, TimeUnit.DAYS);
            return content;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }
}

你可能感兴趣的:(redis,redis,java,数据库)