SpringBoot整合redis配置详解

pom.xml文件中引入依赖

<!--redis依赖-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-pool2</artifactId>
   <version>2.6.1</version>
</dependency>

2.修改yml配置

#缓存模式为redis--值截取部分配置代码,cache和redis的父级配置名是spring
cache:
  type: redis
#redis
redis:
  host: xx.xx.xxx.xxx
  port: 6379
  #使用编号为0的库
  database: 0
  password: redis
  timeout: 100s
  #连接池配置
  jedis:
    pool:
      #最大空闲连接数
      max-idle: 500
      #最小空闲连接数
      min-idle: 50
      #等待可用连接最大时间,负数为无限制
      max-wait: -1s
      #最大活跃连接时间
      max-active: -1

3.在启动主类中添加注解:@EnableCaching

package com.cmh;


import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
 * 启动通用主程序
 *
 * @author chenPC
 */
@MapperScan("com.cmh.mapper")
@SpringBootApplication
@EnableCaching
public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);
    }
}

4.实例说明

 //注解的值为user,key为users_加上返回数据中的username
  //这是拿一个例子,只能返回success或failed,自己可以试着返回数据
@Cacheable(value = "user", key = "'users_'+#username")
@ApiOperation(value = "用户登录MD5", notes = "用户登录MD5")
@GetMapping("/userLogin")
public String userLogin(String username, String password) {
    User result = userService.userLogin(username, password);
    if (result != null) {
        return "success";

    } else {

        return "failed";
    }
    
}

你可能感兴趣的:(java/redis)