SpringBoot+Redis整合
1.在pom.xml添加Redis依賴
<!--整合Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!--整合Redis-->
2.在application.yml配置Redis
#引入Redis 安裝在Linux
jedis :
pool :
host : 192.168.13.128
port : 6379
password: 123456
timeout: 10000
config :
maxTotal: 100
maxIdle: 10
maxWaitMillis : 100000
3.在Resources添加redis.properties
#redis配置開始 # Redis數據庫索引(默認為0) spring.redis.database=0 # Redis服務器地址 spring.redis.host=192.168.13.128 # Redis服務器連接端口 spring.redis.port=6379 # Redis服務器連接密碼(默認為空) spring.redis.password=123456 # 連接池最大連接數(使用負值表示沒有限制) spring.redis.jedis.pool.max-active=1024 # 連接池最大阻塞等待時間(使用負值表示沒有限制) spring.redis.jedis.pool.max-wait=10000 # 連接池中的最大空閑連接 spring.redis.jedis.pool.max-idle=200 # 連接池中的最小空閑連接 spring.redis.jedis.pool.min-idle=0 # 連接超時時間(毫秒) spring.redis.timeout=10000 #redis配置結束 spring.redis.block-when-exhausted=true
4.配置RedisConfiguration.java類,自動注入
@Configuration @PropertySource("classpath:redis.properties") public class RedisConfiguration { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.timeout}") private int timeout; @Value("${spring.redis.jedis.pool.max-idle}") private int maxIdle; @Value("${spring.redis.jedis.pool.max-wait}") private long maxWaitMillis; @Value("${spring.redis.password}") private String password; @Value("${spring.redis.block-when-exhausted}") private boolean blockWhenExhausted; @Bean public JedisPool redisPoolFactory() throws Exception{ System.out.println("JedisPool注入成功!!"); System.out.println("redis地址:" + host + ":" + port); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(maxIdle); jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); // 連接耗盡時是否阻塞, false報異常,ture阻塞直到超時, 默認true jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted); // 是否啟用pool的jmx管理功能, 默認true jedisPoolConfig.setJmxEnabled(true); JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password); return jedisPool; } }
5.配置Util類:序列化類SerializeUtil,參數靜態類RedisConstants,Redis基礎操作類RedisUtil
public class SerializeUtil { public static byte[] serialize(Object object) { ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; try { //序列化 baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(object); byte[] bytes = baos.toByteArray(); return bytes; } catch (Exception e) { } return null; } public static Object unserialize(byte[] bytes) { ByteArrayInputStream bais = null; try { //反序列化 bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { } return null; } /** * 序列化 list 集合 * * @param list * @return */ public static byte[] serializeList(List<?> list) throws Exception { if (list == null || list.size() == 0) { return null; } ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; byte[] bytes = null; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); for (Object obj : list) { oos.writeObject(obj); } bytes = baos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { close(oos); close(baos); } return bytes; } /** * 反序列化 list 集合 * * @param * @return */ public static List<?> unserializeList(byte[] bytes) throws Exception { if (bytes == null) { return null; } List<Object> list = new ArrayList<Object>(); ByteArrayInputStream bais = null; ObjectInputStream ois = null; try { // 反序列化 bais = new ByteArrayInputStream(bytes); ois = new ObjectInputStream(bais); while (bais.available() > 0) { Object obj = (Object) ois.readObject(); if (obj == null) { break; } list.add(obj); } } catch (Exception e) { e.printStackTrace(); } finally { close(bais); close(ois); } return list; } }
public class RedisConstants { public static final String spilt=":"; /** * redis庫0 保存檔案樹 */ public static final Integer datebase0=0; /** * redis庫1 保存檔案樹 */ public static final Integer datebase1=1; /** * 1.redis庫2 保存檔案表格 * 2.保存分頁碼 */ public static final Integer datebase2=2; /** * redis庫3 保存檔案image url */ public static final Integer datebase3=3; /** * 1.redis庫4 保存手機驗證碼 * */ public static final Integer datebase4=4; /** * redis庫5 保存身份認證信息 */ public static final Integer datebase5=5; /** * redis庫6 記錄身份認證次數 */ public static final Integer datebase6=6; /** * redis庫7 記錄重發次數 */ public static final Integer datebase7=7; /** * redis庫8 記錄任務參數 */ public static final Integer datebase8=8; public RedisConstants() { } }
@Component //@Slf4j public class RedisUtil { private static final Log log= LogFactory.getLog(RedisUtil.class); @Autowired private JedisPool jedisPool; public RedisUtil() { } /** * <p> * 通過key獲取儲存在redis中的value * </p> * <p> * 並釋放連接 * </p> * * @param key * @param indexdb 選擇redis庫 0-15 * @return 成功返回value 失敗返回null */ public String get(String key,int indexdb) { Jedis jedis = null; String value = null; try { jedis = jedisPool.getResource(); jedis.select(indexdb); value = jedis.get(key); System.out.println(value); // log.info(value); } catch (Exception e) { log.error(e.getMessage()); } finally { returnResource(jedisPool, jedis); } return value; } /** * <p> * 通過key獲取儲存在redis中的value * </p> * <p> * 並釋放連接 * </p> * * @param key * @param indexdb 選擇redis庫 0-15 * @return 成功返回value 失敗返回null */ public byte[] get(byte[] key,int indexdb) { Jedis jedis = null; byte[] value = null; try { jedis = jedisPool.getResource(); jedis.select(indexdb); value = jedis.get(key); } catch (Exception e) { log.error(e.getMessage()); } finally { returnResource(jedisPool, jedis); } return value; } }
6.在Controller添加操作類RedisController
@Controller @RequestMapping(value="/redis") public class RedisController{ @Autowired RedisUtil redisUtil; @Autowired AccountService accountService; @RequestMapping(value = "getRedis",method = RequestMethod.POST) @ResponseBody public ModelMap getRedis() throws Exception { //存儲String // redisUtil.set("20182019","這是一條測試數據1", RedisConstants.datebase1); // Long resExpire = redisUtil.expire("20182018", 60, RedisConstants.datebase1);//設置key過期時間 // String res = redisUtil.get("20182019", RedisConstants.datebase1); // String name = redisUtil.get("name", RedisConstants.datebase0); // //存儲hash-map // Map<String, String> map=new HashMap<String,String>(); // map.put("a","a1"); // map.put("b","a2"); // map.put("c","a2"); // redisUtil.hmset("dd",map,RedisConstants.datebase1); // List<String> list111 = (List<String>) redisUtil.getList("testlist"); // System.out.println(list111); //存儲list serialize // List<UserVO> userList=accountService.selsetUserList(); // System.out.println(userList); // for(UserVO user:userList){ // redisUtil.lpush(RedisConstants.datebase1,"userList",user.getUserid()+""); // redisUtil.hset("user:"+user.getUserid(),"userId",user.getUserid()+""); // redisUtil.hset("user:"+user.getUsername(),"userName",user.getUsername()+""); // redisUtil.hset("user:"+user.getEmail(),"usereEail",user.getEmail()+""); // // } //獲取List數據 String userId= redisUtil.hget("userList:"+1,"userId"); String userName= redisUtil.hget("userList:"+1,"userName"); String userEmail= redisUtil.hget("userList:"+1,"userEmail"); System.out.println(userId); System.out.println(userName); System.out.println(userEmail); return null; } }
