Adding dependencies in the project Pom.xml file
<!-- 添加jedis依赖 --><dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId></dependency>
Locate the Application.properties file in the project resources directory to add Reids configuration information
# redisredis.host=10.x.x.xredis.port=6379 //redis端口redis.timeout=3redis.password=xxxxredis.poolMaxTotal=10 //最大连接池redis.poolMaxIdle=10 //最大休闲连接redis.poolMaxWait=3
First we need to define a Redisconfig configuration class that sets and gets the relevant properties of Redis through this configuration class
@Component @configurationproperties (prefix= "Redis") public class Redisconfig {private String host; private int port; private String password; private int timeout; private int poolmaxtotal; private int poolmaxidle; private int poolmaxwait; Public String GetHost () {return host; The public void Sethost (String host) {this.host = host; } public int Getport () {return port; } public void Setport (int port) {this.port = port; } public String GetPassword () {return password; } public void SetPassword (String password) {this.password = password; } public int GetTimeout () {return timeout; } public void SetTimeout (int timeout) {this.timeout = timeout; } public int Getpoolmaxtotal () {return poolmaxtotal; } public void Setpoolmaxtotal (int poolmaxtotal) {this.poolmaxtotal = Poolmaxtotal; } public int Getpoolmaxidle () {return PoolmaxiDle } public void Setpoolmaxidle (int poolmaxidle) {this.poolmaxidle = Poolmaxidle; } public int getpoolmaxwait () {return poolmaxwait; } public void setpoolmaxwait (int poolmaxwait) {this.poolmaxwait = poolmaxwait; }}
Next, we will test the success of the connection to Redis. SpringBoot->Controller
Write a value function in the layer that gets a key
Usually the control layer calls the service layer method, that is, we want to get the instance object of the Jedis class in the service layer, and finally we call the relevant method jedis.get(key)
to get the value of the key.
The control layer code is as follows
@Controllerpublic class DemoController { @Autowired RedisService redisService; @RequestMapping("/db/getredis") @ResponseBody public Result<String> getRedis() { String strVal = redisService.getInstance().get("k1"); return Result.success(strVal); }}
The service layer code is as follows
@Servicepublic class RedisService { @Autowired JedisPool jedisPool; public Jedis getInstance(){ Jedis jedis = jedisPool.getResource(); return jedis; }}
Springboot How to integrate Jedis