目录
基本概念
SpringBoot提供了一套Redis接口,但个人感觉没Jedis方便(可能是因为本人比较菜的原因吧)
在此封装了相爱Jedis,在部署的时候,同样可以使用。
这里先说明下Redis
Redis中数据以Hash进行存储的。
跑的使用同样使用java -jar xxxxx.jar --redis.host=xxxx.xxxx.xxxx即可!
新增springRedis.xml,进行Spring相关的配置
同样使用Service层进行调用
代码与实例
关键代码,SpringBean加载:
package com.process.demo.spring;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringBeanHolder implements ApplicationContextAware {
private static ApplicationContext ac;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ac = applicationContext;
}
public static Object getBean(String beanName){
return ac.getBean(beanName);
}
public static<T> T getBean(Class<T> clazz){
return ac.getBean(clazz);
}
}
在Main函数中直接new即可:
package com.process.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("springRedis.xml");
SpringApplication.run(DemoApplication.class, args);
}
}
RedisUtils.java
package com.process.demo.utils;
import com.process.demo.spring.SpringBeanHolder;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class RedisUtils {
private static JedisPool jedisPool = null;
static {
jedisPool = (JedisPool) SpringBeanHolder.getBean("jedisPool");
}
public static Set<String> getKeysListByVagueWord(String key){
Jedis jedis = jedisPool.getResource();
Set<String> keys = jedis.keys("*" + key);
jedis.close();
return keys;
}
public static Map<String, String> getHGetAllByKey(String key){
Jedis jedis = jedisPool.getResource();
Map<String, String> map = jedis.hgetAll(key);
jedis.close();
return map;
}
public static Set<String> getHKeysByKey(String key){
Jedis jedis = jedisPool.getResource();
Set<String> hkeys = jedis.hkeys(key);
jedis.close();
return hkeys;
}
public static List<String> getHValueByKey(String key){
Jedis jedis = jedisPool.getResource();
List<String> hvals = jedis.hvals(key);
jedis.close();
return hvals;
}
}
源码下载
地址:https://github.com/fengfanchen/Java/tree/master/MyJedisInSpringBoot