SpringBoot整合redis把用户登录信息存入redis
程序员文章站
2022-03-25 18:00:26
SpringBoot整合redis把用户登录信息存入redis ......
首先引入redis的jai包
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-redis</artifactid> </dependency>
在userserviceimpl引用springboot自带的stringredistemplate
@autowired private stringredistemplate stringredistemplate;
在userserviceimpl中通过usermapper查询到用户名和密码等用户信息后
插入到redis后要在获取key的话要用到cookie了,把key存到cookie中,取的时候在cookie中取
//把user实体类转化成json格式 string userjoin = json.tojsonstring(user); if (user != null) { //获取uuid string uuid = uuidutils.getuuid(); //创建cookie cookie cookie = new cookie("usercookie", uuid); response.addcookie(cookie); //把用户信息存入redis set(key,value,过期时长,过期格式) 设置三天过期 stringredistemplate.opsforvalue().set("user" + "/" + uuid, userjoin, 3, timeunit.days); return msg.ok(""); } else { return msg.failure("用户名或密码错误"); }
然后在usercontroller获取的时候
@requestmapping(value = "/tomainpage") public modelandview tomainpage(httpservletrequest request, httpservletresponse response) { modelandview mv; string struuid = null; //获取cookie里面的uuid cookie[] cookies = request.getcookies(); for (cookie cookie : cookies) { if (cookie.getname().equalsignorecase("usercookie")) { struuid = cookie.getvalue(); } } if (struuid == null) { system.out.println("验证不通过"); system.out.println("uuid不存在"); } string userjson; try { //根据struuid,在redis中获取user信息 userjson = stringredistemplate.opsforvalue().get("user" + "/" + struuid); jsonobject pa = jsonobject.parseobject(userjson); if ("管理员".equals(pa.getstring("urank")) && userjson != null) { mv = new modelandview("index"); mv.addobject("user", pa.getstring("uname")); mv.addobject("id", pa.getstring("id")); mv.addobject("upwd", pa.getstring("upwd")); } else if ("普通用户".equals(pa.getstring("urank")) && userjson != null) { mv = new modelandview("pt_index"); mv.addobject("user", pa.getstring("uname")); mv.addobject("id", pa.getstring("id")); mv.addobject("upwd", pa.getstring("upwd")); } else { mv = new modelandview("redirect:login"); } } catch (exception e) { // todo auto-generated catch block mv = new modelandview("redirect:login"); } return mv; }