导入依赖 => 配置连接 => 测试
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
源码分析:
@Bean
//不存在才生效=>我们可以自己定义一个redisTemplate替换这个默认的
@ConditionalOnMissingBean(name = {"redisTemplate"})
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
//默认的RedisTemplate,没有过多的设置,redis对象都是需要序列化的
//两个泛型都是Object类型,使用时需要进行强制转换
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean //String是redis最常使用的,所以单独提出来一个bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
配置:
# SpringBoot 所有的配置类,都有一个自动配置类:RedisAutoConfiguration
# 自动配置类都会绑定一个 properties:RedisProperties
spring:
redis:
host: 127.0.0.1
port: 6379
# lettuce.xxx SpringBoot2.x使用这个才能生效
# jedis.xxx
测试
@SpringBootTest
class RedisSpringbootApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
/*
//redisTemplate 操作不同的数据类型,api和我们的指令是一样的
//opsForValue().xxx 操作字符串,类似String
//opsForList().xxx 操作List,类似List
//opsForSet()
//opsForHash()
//等等各种数据结构
String s = redisTemplate.opsForValue().toString();
//获取redis的链接对象
//除了基本的操作,我们常用的方法都可以直接通过redisTemplate操作,比如事务,和基本的CRUD
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
connection.flushDb();
connection.flushAll();
*/
redisTemplate.opsForValue().set("mykey","你好,Redis!");
System.out.println(redisTemplate.opsForValue().get("mykey"));
}
}
@Test
public void test() throws JsonProcessingException {
//开发中一般都使用json来传递对象
User user = new User("peng", 25);
//所有的对象都需要序列化
String jsonUser = new ObjectMapper().writeValueAsString(user);
redisTemplate.opsForValue().set("user",jsonUser);
System.out.println(redisTemplate.opsForValue().get("user"));
}
一般在pojo中序列化
public class User implements Serializable{
private String name;
private int age;
}
我们编写一个自己的redisTemplate,com.peng.config.RedisConfig.java
@Configuration
public class RedisConfig {
//编写我们自己的 redisTemplate,一个固定的模板
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
//我们我了自己开发方便,一般直接使用<String,Object>类型
RedisTemplate<String,Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
//配置具体的序列化方式,这里是json
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
//String的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
//hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
//value的序列化方式采用json
template.setValueSerializer(jackson2JsonRedisSerializer);
//hash的value的序列化方式采用json
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
自己封装的redis工具
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String,Object> redisTemplate;
//==============Common===============
//缓存失效时间
public boolean expire(String key, long time){
try {
if (time > 0){
redisTemplate.expire(key,time, TimeUnit.SECONDS);
}
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
//根据key获取过期时间
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
//判断key是否存在
public boolean hasKey(String key){
try {
return redisTemplate.hasKey(key);
}catch (Exception e){
e.printStackTrace();
return false;
}
}
//删除存缓
public void del(String... key){
if (key != null && key.length > 0){
if (key.length == 1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete(Arrays.asList(key));
}
}
}
//普通缓存获取
public Object get(String key){
return key == null ? null : redisTemplate.opsForValue().get(key);
}
//普通存缓放入
public boolean set(String key,Object value){
try {
redisTemplate.opsForValue().set(key,value);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
//普通存缓放入并设置时间
public boolean set(String key,Object value,long time){
try {
if (time > 0){
redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
}else {
set(key, value);
}
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
//递增
public long incr(String key,long delta){
if (delta < 0){
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
//递减
public long decr(String key,long delta){
if (delta < 0){
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//==============Map===============
//==============Set===============
}
redis
NoSQL,键值对存储
应用
UserController.java
@GetMapper("/getUser")
@ResponseBody
public Object getUser(){
if (redisUtil.hasKey("user")){ //如果redis里有就从redis里返回
return redisUtil.get("user");
}
RedisUtil redisUtil = new RedisUtil();
userJson = redisUtil.get("user");
return userJson;
}