二、redis配置org.springframework.boot spring-boot-starter-data-redis2.4.2 io.lettuce lettuce-core
#redis 配置
redis:
database: 15
host: 127.0.0.1
lettuce:
pool:
max-active: 8 #最大连接数据库连接数,设 0 为没有限制
max-idle: 8 #最大等待连接中的数量,设 0 为没有限制
max-wait: -1ms #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
min-idle: 0 #最小等待连接中的数量,设 0 为没有限制
shutdown-timeout: 100ms
password: ''
port: 6379
三、定义redis用到的Constants类
public class RedisKeyConstant {
public static final String PREFIX_USER_TOKEN = "user:token:";
}
四、编写redis工具类
- 常用的基本都在这里了
@Repository public class RedisUtil五、UserCache{ private static Logger logger = LoggerFactory.getLogger(RedisUtil.class); @Resource private StringRedisTemplate stringRedisTemplate; public void expire(String key, long time) { if (time > 0) { stringRedisTemplate.expire(key, time, TimeUnit.SECONDS); } } public long getExpireTime(String key) { return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS); } public boolean hasKey(String key) { if (key == null) { return false; } return stringRedisTemplate.hasKey(key); } public void del(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { stringRedisTemplate.delete(key[0]); } else { stringRedisTemplate.delete(Arrays.asList(key)); } } } // =============================================================== // // =========================== String ============================ // // =============================================================== // public Object get(String key) { return key == null ? null : stringRedisTemplate.opsForValue().get(key); } public boolean set(String key, String value) { try { stringRedisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { logger.error(e.toString()); return false; } } public boolean set(String key, String value, long time) { try { if (time > 0) { stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { logger.error(e.toString()); return false; } } public long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递增因子必须大于0"); } return stringRedisTemplate.opsForValue().increment(key, delta); } public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return stringRedisTemplate.opsForValue().increment(key, -delta); } // =============================================================== // // ============================ Hash ============================= // // =============================================================== // public Object hget(String key, String item) { return stringRedisTemplate.opsForHash().get(key, item); } public Map
@Repository
public class UserCache {
@Autowired
private RedisDao redisDao;
public boolean setToken(String token, String userId) {
return redisDao.set(RedisKeyConstant.PREFIX_USER_TOKEN + token, userId, CommonConstant.UNIT_HOUR * 3);
}
@Async
public void refreshToken(String token) {
redisDao.expire(RedisKeyConstant.PREFIX_USER_TOKEN + token, CommonConstant.UNIT_HOUR * 3);
}
@Async
public void delToken(String token) {
redisDao.del(RedisKeyConstant.PREFIX_USER_TOKEN + token);
}
public String getUserIdByToken(String token) {
return (String) redisDao.get(RedisKeyConstant.PREFIX_USER_TOKEN + token);
}
}
六、使用redis实现用户登录后token的缓存
**********************************简单实现用户登录************************************1、用户登录的Controller
@RestController
@RequestMapping("/sys/")
@Api(tags = "用户登录")
@Slf4j
public class LoginController {
@Autowired
private SysLoginService sysLoginService;
@ApiOperation("登录接口")
@RequestMapping(value = "login", method = RequestMethod.POST)
public Rsp login(@RequestBody SysLogin sysLogin) {
SysLoginResp login = sysLoginService.login(sysLogin);
return Rsp.ok(RspConstant.MSG_SUCCESS, login);
}
}
2、用户登录的Service+Impl
public interface SysLoginService {
SysLoginResp login(SysLogin sysLogin);
}
@Service
public class SysLoginServiceImpl implements SysLoginService {
@Autowired
private SysUserEntityDao sysUserEntityDao;
@Autowired
private UserCache userCache;
@Override
public SysLoginResp login(SysLogin sysLogin) {
String username = sysLogin.getUsername();
SysUserEntity user = sysUserEntityDao.getUserInfoByUserName(username);
// 1.校验用户是否有效
this.checkUserIsEffective(user, sysLogin);
SysLoginResp loginResp = new SysLoginResp();
loginResp.setToken(IdUtil.nanoId());
boolean res = userCache.setToken(loginResp.getToken(), user.getId().toString());
if (!res) {
throw new RuntimeException("登录缓存失败,请重试");
}
return loginResp;
}
private void checkUserIsEffective(SysUserEntity user, SysLogin sysLogin){
// 1.用户为空的情况
if (null == user) {
throw new RuntimeException("账号不存在");
}
// 2.账号注销情况
if (CommonConstant.DEL_FLAG_1.equals(user.getDelFlag())) {
throw new RuntimeException("该用户已注销");
}
// 3.账号冻结情况
if (CommonConstant.USER_STATUS_2.equals(user.getStatus())) {
throw new RuntimeException("该账号处于冻结状态");
}
// 4.用户不为空情况
String currenUserPassword = PasswordUtil.encrypt(sysLogin.getUsername(), sysLogin.getPassword(), user.getSalt());
String dbPassword = user.getPassword();
if (!currenUserPassword.equals(dbPassword)) {
throw new RuntimeException("密码错误");
}
}
}
3、dao
@Repository
public class SysUserEntityDao {
@Autowired
private SysUserEntityMapper sysUserEntityMapper;
public SysUserEntity getUserInfoByUserName(String username) {
return sysUserEntityMapper.selectOne(
new LambdaQueryWrapper()
.eq(SysUserEntity::getUsername, username)
);
}
}
4、实体
@Data
@ApiModel(value="登录对象", description="登录对象")
public class SysLogin {
@ApiModelProperty(value = "账号")
@NonNull
private String username;
@ApiModelProperty(value = "密码")
@NonNull
private String password;
}
@ApiModel(description = "登录结果返回对象")
public class SysLoginResp {
@ApiModelProperty("token")
private String token;
public SysLoginResp() {
}
public SysLoginResp(String token) {
this.token = token;
}
@Override
public String toString() {
return "SysLoginResp{" +
"token='" + token + ''' +
'}';
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
希望对您有帮助,感谢观看



