spring-boot 和Redis 整合
pom.xml
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.8.0</version>
</dependency>
application.properties
spring.redis.host=127.0.0.1
spring.redis.port=6379
RedisConfig.java
package top.xiongmingcai.cache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
@Configuration
@Slf4j
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Bean(name = "redisPool")
public JedisPool jedisPool() {
log.info("JedisPoll连接成功:" + host + "\t" + port);
return new JedisPool(host, port);
}
}
RedisClient.java
package top.xiongmingcai.cache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
@Configuration
@Slf4j
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Bean(name = "redisPool")
public JedisPool jedisPool() {
log.info("JedisPoll连接成功:" + host + "\t" + port);
return new JedisPool(host, port);
}
}
CacheController.java
package top.xiongmingcai.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import top.xiongmingcai.cache.RedisClient;
import javax.annotation.Resource;
@Controller
@RequestMapping("/cache")
@Slf4j
public class CacheController {
@Resource private RedisClient redisClient;
@RequestMapping(value = "/set", method = RequestMethod.GET)
@ResponseBody
public String get(
@RequestParam(value = "k", defaultValue = "hello") String k,
@RequestParam(value = "v", defaultValue = "hello") String v) {
try {
redisClient.set(k, v);
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
@RequestMapping(value = "/get", method = RequestMethod.GET)
@ResponseBody
public String get(@RequestParam(value = "k", defaultValue = "hello") String k) {
try {
String result = redisClient.get(k);
log.info("result = {}", result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
}