Java教程

springboot中@Cache和redis的使用

本文主要是介绍springboot中@Cache和redis的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1导入redis依赖

         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2.配置redis

spring:
  datasource:
    url: jdbc:mysql:///sx
    username: root
    password:
    driver-class-name: com.mysql.jdbc.Driver
#  cache:
#    type: redis

  redis:
    host: 127.0.0.1
    port: 6379

3.启动类上开启缓存

@SpringBootApplication
@MapperScan("com.upb.dao")
@EnableCaching //开启缓存
public class UpbApplication {

    public static void main(String[] args) {
        SpringApplication.run(UpbApplication.class, args);
    }

}

4.编写控制器层

@Controller
@Api( tags = "登录接口")
public class LoginController {
    @Autowired
    Result result;
    @Autowired
    UserService userService;


    @ResponseBody
    //说明是什么方法(可以理解为方法注释)
    @RequestMapping("/login")
    @Cacheable(value = "r-test")
    public Result login( @RequestBody User user){
        System.out.println(userService.getAll());
        result.Successful("cg");
        return result;
    }

}

5.由于刚学redis,没用过注解,百度了很多,最后自己才知道@Cacheable中的value=“你redis中的key”‘,就相当于给你主动存到了redis中。

 欧克记录一下,其它的详细作用可以看看其他文档。

这篇关于springboot中@Cache和redis的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!