- 步骤
1。导入相关依赖,配置yml
org.springframework.boot spring-boot-starter-data-redisorg.springframework.boot spring-boot-starter-testorg.springframework.session spring-session-coreorg.springframework.session spring-session-data-redis
redis: host: localhost port: 6379 jedis.pool.max-idle: 100 jedis.pool.max-wait: -1ms jedis.pool.min-idle: 2 timeout: 2000m
2.启动类上加入注解
@EnableRedisHttpSession
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import springfox.documentation.swagger2.annotations.EnableSwagger2; import tk.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.fzw.dao") @EnableSwagger2 @EnableRedisHttpSession public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args);} }
3.在controller的方法上传入HttpServletRequest对象,例如本例中希望实现第一次登录是从数据库中查询数据,但是后面再次访问时,从redis缓存中获取数据,这样减少数据库的压力
@ApiOperation(value = "登录 ",notes = "登录 ") @PostMapping("/login") public Result login(@RequestBody BookUser bookUser, HttpServletRequest request) { Listlist=bookUserService.select(bookUser); if(list.size()>0){ if(request.getAttribute("flag")==null){ //第一次登录 request.getSession().setAttribute("flag","true"); System.out.println(request.getSession().getAttribute("flag")); } return new Result(true,200,"登录成功"); }else{ return new Result(true,500,"用户名或密码错误"); } } }
service层
public PageInfofindAllByPage(Integer currentPage, Integer pageSize, HttpServletRequest request) { PageHelper.startPage(currentPage, pageSize); PageInfo pageInfo = new PageInfo<>(); Object flag = request.getSession().getAttribute("flag"); System.out.println(request.getSession().getAttribute("flag")); if (flag==null|| "true".equals(flag)) { //第一次 登录 // 通过数据库查询 List bookList = bookMapper.selectAll(); pageInfo = new PageInfo(bookList); System.out.println("走数据库"); request.getSession().setAttribute("booklist", bookList); request.getSession().setAttribute("flag", "false"); } else { //通过 redis查询 // 封装PageInfo 对象 pageInfo = new PageInfo((List) request.getSession().getAttribute("booklist")); System.out.println("走redis"); } System.out.println("pageInfo的 值" + pageInfo); return pageInfo; }
在访问到该地址后,redis会自动创建redis对象
同时启动多个Springboot应用测试
本例中通过nginx实现负载均衡,nginx配置如下
nginx.conf
代码还是有些问题的,欢迎大家评论交流。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)