Redis簡介
Redis數據庫是一個完全開源免費的高性能Key-Value數據庫。它支持存儲的value類型有五種,包括string(字符串)、list(鏈表)、set(集合)、zset(sorted set –有序集合)和hash(哈希類型)
Redis非常快,每秒可執行大約110000次的設置(SET)操作,每秒大約可執行81000次的讀取/獲取(GET)操作。
StringTemplate和RedisTemplate說明
StringTemplate和RedisTemplate是Spring封裝的兩個對象,用來對redis進行操做。
- 兩者的關係是StringRedisTemplate繼承RedisTemplate;
- 兩者的數據是不共通的;也就是說StringRedisTemplate只能管理StringRedisTemplate裏面的數據,RedisTemplate只能管理RedisTemplate中的數據;
- SDR默認採用的序列化策略有兩種,一種是String的序列化策略,一種是JDK的序列化策略;
- StringRedisTemplate默認採用的是String的序列化策略,保存的key和value都是採用此策略序列化保存的;
- RedisTemplate默認採用的是JDK的序列化策略,保存的key和value都是採用此策略序列化保存的;
所以,我們在使用的過程中可以根據存儲數據類型來選擇操作redis數據的對象。
- 當存儲的數據爲字符串類型的時候,我們選擇使用StringRedisTemplate對象來操作reids;
- 當存儲的數據類型爲複雜的對象類型的時候,我們選擇使用RedisTemplate對象來操作redis,這樣我們可以直接從redis中取出一個對象,而不需要進行數據轉換;
Maven依賴配置
<!-- 引入 spring-boot-starter-web 依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 引入 spring-boot-starter-data-redis 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 引入 fastjson 依賴 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!-- 引入 spring-boot-starter-test 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
application.properties配置
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=adm123456
spring.redis.timeout=5000
spring.redis.jedis.pool.max-active=1000
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=30
spring.redis.jedis.pool.min-idle=10
SpringBoot啓動類
package com.yuanx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
*
* @ClassName: DemoApplication
* @Description: Demo啓動類
* @author YuanXu
* @date 2019年7月5日 下午4:09:33
*
*/
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(DemoApplication.class);
}
/**
* @Title main
* @Description Demo啓動入口
* @author YuanXu
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Redis配置類
package com.yuanx.config;
import java.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
*
* @ClassName: RedisConfiguration
* @Description: Redis配置類
* @author YuanXu
* @date 2019年7月5日 下午4:23:23
*
*/
@Configuration
public class RedisConfiguration {
@SuppressWarnings("unused")
private static Logger log = LoggerFactory.getLogger(RedisConfiguration.class);
/**
*
* @Title: redisTemplate
* @Description: RedisTemplate Bean聲明
* @author YuanXu
* @param connectionFactory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值(默認使用JDK的序列化方式)
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 使用StringRedisSerializer來序列化和反序列化redis的key值
RedisSerializer<?> redisSerializer = new StringRedisSerializer();
// key
redisTemplate.setKeySerializer(redisSerializer);
redisTemplate.setHashKeySerializer(redisSerializer);
// value
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
PO實體類
package com.yuanx.demo.po;
import java.io.Serializable;
import java.util.Date;
public class DemoPO implements Serializable {
private static final long serialVersionUID = 1186292279688874773L;
private String name;
private Integer age;
private String sex;
private Boolean admin;
private String desc;
private Date lastUpdDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Boolean getAdmin() {
return admin;
}
public void setAdmin(Boolean admin) {
this.admin = admin;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Date getLastUpdDate() {
return lastUpdDate;
}
public void setLastUpdDate(Date lastUpdDate) {
this.lastUpdDate = lastUpdDate;
}
}
RedisService接口類
package com.yuanx.demo.service;
/**
*
* @ClassName: IRedisService
* @Description: Redis數據服務
* @author YuanXu
* @date 2019年7月5日 下午5:06:52
*
*/
public interface IRedisService {
/**
*
* @Title: setStr
* @Description: TODO(這裏用一句話描述這個方法的作用)
* @author YuanXu
* @param key
* @param value
*/
public Boolean setStr(String key, String value);
/**
*
* @Title: getStr
* @Description: TODO(這裏用一句話描述這個方法的作用)
* @author YuanXu
* @param key
* @return
*/
public String getStr(String key);
/**
*
* @Title: delStr
* @Description: TODO(這裏用一句話描述這個方法的作用)
* @author YuanXu
* @param key
*/
public Boolean delStr(String key);
/**
*
* @Title: setObj
* @Description: TODO(這裏用一句話描述這個方法的作用)
* @author YuanXu
* @param key
* @param obj
*/
public <T> Boolean setObj(String key, T obj);
/**
*
* @Title: getObj
* @Description: TODO(這裏用一句話描述這個方法的作用)
* @author YuanXu
* @param key
* @return
*/
public <T> T getObj(String key);
/**
*
* @Title: delObj
* @Description: TODO(這裏用一句話描述這個方法的作用)
* @author YuanXu
* @param key
*/
public Boolean delObj(String key);
}
RedisService實現類
package com.yuanx.demo.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.yuanx.demo.service.IRedisService;
@Service
public class RedisServiceImpl implements IRedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public Boolean setStr(String key, String value) {
Boolean flag = true;
try {
stringRedisTemplate.opsForValue().set(key, value);
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
return flag;
}
@Override
public String getStr(String key) {
String value = null;
try {
value = stringRedisTemplate.opsForValue().get(key);
} catch (Exception e) {
e.printStackTrace();
value = null;
}
return value;
}
@Override
public Boolean delStr(String key) {
Boolean flag = true;
try {
flag = stringRedisTemplate.delete(key);
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
return flag;
}
@Override
public <T> Boolean setObj(String key, T obj) {
Boolean flag = true;
try {
redisTemplate.opsForValue().set(key, obj);
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
return flag;
}
@Override
@SuppressWarnings("unchecked")
public <T> T getObj(String key) {
T value = null;
try {
Object obj = redisTemplate.opsForValue().get(key);
if (obj != null) {
value = (T) obj;
}
} catch (Exception e) {
e.printStackTrace();
value = null;
}
return value;
}
@Override
public Boolean delObj(String key) {
Boolean flag = true;
try {
flag = redisTemplate.delete(key);
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
return flag;
}
}
JUnit測試類
package com.yuanx.test;
import java.util.Date;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.yuanx.DemoApplication;
import com.yuanx.demo.po.DemoPO;
import com.yuanx.demo.service.IRedisService;
/**
*
* @ClassName: DemoTest
* @Description: Demo測試類
* @author YuanXu
* @date 2019年7月5日 下午4:21:25
*
*/
@RunWith(value = SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { DemoApplication.class })
public class DemoTest {
@Autowired
private IRedisService redisService;
@Test
public void doTest() {
redisService.setStr("test", "00000");
String value = redisService.getStr("test");
System.out.println(value);
DemoPO po = new DemoPO();
po.setName("測試數據");
po.setAge(20);
po.setAdmin(true);
po.setSex("男");
po.setLastUpdDate(new Date());
redisService.setObj("test2", po);
DemoPO po2 = redisService.getObj("test2");
System.out.println(po2.getName());
System.out.println("單元測試執行完畢");
}
}
單元測試結果
哈哈