在上一篇我讲的了怎么搭建一个redis的服务平台,服务搭建好了 我们就要应用,这篇文章主要是讲redis如何集成springboot对redis进行操作。
首先我们需要构建一个springboot的项目,当然这个很简单,也可以学习我接下来写的一篇关于springboot的文章。
轻松构建一个springboot:
新建一个meven项目,导入springboot的包
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
然后在最顶层目录下新建一个MiaoShaApp.java
代码如下:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MiaoShaApp {
public static void main(String[] args) {
SpringApplication.run(MiaoShaApp.class, args);
}
}
再在controller目录下新建一个SampleController.java:
@Controller
@RequestMapping("/test")
public class SampleController {
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
}
执行MiaoshaApp的main方法,启动容器,访问localhost:8080/test 一个web项目就搭建好了 ,是不是够快啊。
接下来是对reids的集成,不多说都懂直接引入依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
配置application.xml
#redis
redis.host=ip
redis.port=6379
redis.timeout=10
redis.password=123456
redis.poolMaxTotal=1000
redis.poolMaxIdle=500
redis.poolMaxWait=500
读取redis配置文件
@Component
@ConfigurationProperties(prefix = "redis") //redis打头的都读取出来
public class RedisConfig {
private String host;
private int port;
private int timeout;//秒
private String password;
private int poolMaxTotal;
private int poolMaxIdle;
private int poolMaxWait;//秒
//getter setter
}
创建jedispool
JedisPool
@Service
public class RedisPoolFactory {
@Autowired
RedisConfig redisConfig;
@Bean
public JedisPool jedisPoolFactory(){
JedisPoolConfig jpc = new JedisPoolConfig();
jpc.setMaxIdle(redisConfig.getPoolMaxIdle());
jpc.setMaxTotal(redisConfig.getPoolMaxTotal());
jpc.setMaxWaitMillis(redisConfig.getPoolMaxWait()*1000);
JedisPool jp = new JedisPool(jpc, redisConfig.getHost(),redisConfig.getPort(),redisConfig.getTimeout()*1000,redisConfig.getPassword(),0);
return jp;
}
}
对redis服务进行封装:
@Service
public class RedisService {
@Autowired
JedisPool jedisPool;
public <T> T get(KeyPrefix prefix,String key,Class<T> clazz){
System.out.println("get----");
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
System.out.println(jedis);
String relalyKey = prefix.getPrefix() +key;
String str = jedis.get(relalyKey);
System.out.println(str);
T t = strToBean(str,clazz);
return t;
} catch (Exception e) {
e.printStackTrace();
returnToPool(jedis);
}finally {
returnToPool(jedis);
}
return null;
};
/**
* 设置缓存
* @param key
* @param value
* @return
*/
public <T> boolean set(KeyPrefix prefix,String key,T value){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String str = beanToStr(value);
if (str == null||str.length()<=0) {
return false;
}
String realyKey = prefix.getPrefix()+key;
int seconds = prefix.expirSeconds();
if (seconds<=0) {//永不过期
jedis.set(realyKey, str);
}else {//seconds过期时间
jedis.setex(realyKey, seconds, str);
}
return true;
} catch (Exception e) {
returnToPool(jedis);
}
return true;
};
/**
* 判断key是否存在
* */
public <T> boolean exists(KeyPrefix prefix,String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix()+key;
return jedis.exists(realKey);
} catch (Exception e) {
e.printStackTrace();
}finally {
returnToPool(jedis);
}
return false;
}
/**
* 删除缓存
* @param prefix
* @param key
* @return
*/
public boolean delete(KeyPrefix prefix,String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String realyKey = prefix.getPrefix()+key;
Long del = jedis.del(realyKey);
return del>0;
} catch (Exception e) {
e.printStackTrace();
}finally {
returnToPool(jedis);
}
return false;
}
/**
* 增加
* @param prefix
* @param key
* @return
*/
public <T> Long incr(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String realyKey=prefix.getPrefix()+key;
jedis.incr(realyKey);
} catch (Exception e) {
e.printStackTrace();
}finally {
returnToPool(jedis);
}
return null;
}
/**
* 减少
* @param prefix
* @param key
* @return
*/
public <T> Long decr(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String realyKey=prefix.getPrefix()+key;
jedis.decr(realyKey);
} catch (Exception e) {
e.printStackTrace();
}finally {
returnToPool(jedis);
}
return null;
}
public boolean delete(KeyPrefix prefix) {
if(prefix == null) {
return false;
}
List<String> keys = scanKeys(prefix.getPrefix());
if(keys==null || keys.size() <= 0) {
return true;
}
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.del(keys.toArray(new String[0]));
return true;
} catch (final Exception e) {
e.printStackTrace();
return false;
} finally {
if(jedis != null) {
jedis.close();
}
}
}
public List<String> scanKeys(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
List<String> keys = new ArrayList<String>();
String cursor = "0";
ScanParams sp = new ScanParams();
sp.match("*"+key+"*");
sp.count(100);
do{
ScanResult<String> ret = jedis.scan(cursor, sp);
List<String> result = ret.getResult();
if(result!=null && result.size() > 0){
keys.addAll(result);
}
//再处理cursor
cursor = ret.getStringCursor();
}while(!cursor.equals("0"));
return keys;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
private <T> String beanToStr(T value) {
if (value==null) {
return null;
}
Class<?> clazz = value.getClass();
if (clazz == int.class||clazz == Integer.class) {
return ""+value;
}else if (clazz == String.class) {
return (String)value;
}else if (clazz == Long.class||clazz == long.class) {
return ""+value;
}else {
return JSON.toJSONString(value);
}
}
@SuppressWarnings("unchecked")
private <T> T strToBean(String str,Class<T> clazz) {
if (str==null || str.length()<=0) {
return null;
}
if (clazz == int.class||clazz == Integer.class) {
return (T) Integer.valueOf(str);
}else if (clazz == String.class) {
return (T) str;
}else if (clazz == Long.class||clazz == long.class) {
return (T) Long.valueOf(str);
}else {
return JSON.toJavaObject(JSON.parseObject(str), clazz);
}
}
private void returnToPool(Jedis jedis) {
if (jedis!=null) {
jedis.close();
}
}
}
接下来你就可以直接用redisService开始操作redis
@Autowired
RedisService redisService;
@RequestMapping("/redis/get")
@ResponseBody
public Result<MiaoShaUser> getredis(){
MiaoShaUser user = redisService.get(UserKey.getbyName,""+1,MiaoShaUser.class);
return Result.success(user);
}
@RequestMapping("/redis/set")
@ResponseBody
public Result<Boolean> setredis(){
MiaoShaUser user = new MiaoShaUser();
user.setUsername("小名");
user.setPassword("1111");
user.setId(1l);
Boolean isset = redisService.set(UserKey.getbyName,""+1 ,user);
return Result.success(isset);
}