Redis主要用于处理数据的高效访问以及热点数据存储
1原子性单线程, 只是通过多线程优化了网络IO操作,执行命令仍然是单线程的,通过指令的单线程操作从而避免了冲突问题的出现。
2持久化
3redis底层良好的数据结构设计Redis3.2
redis-server --service-install redis.windows.conf --loglevel verbose
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
修改application.yml,配置redis连接信息
spring:可以是字符串、整数、**浮点数类型
redis:
host: 192.168.200.151
port: 6379
添加redis配置类
package com.itheima.reggie.config;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
return redisTemplate;
}
}
@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void addInfo(){
redisTemplate.opsForValue().set("name","zhangsan");
redisTemplate.opsForValue().set("age",18,5, TimeUnit.SECONDS);
}
@Test
public void getInfo(){
redisTemplate.opsForValue().get("name");
}
@Test
public void setExpire(){
redisTemplate.delete("name");
}
}
以商品详情页为例,假设现在客户端有大量请求在查询商品详情信息, 如果直接基于数据库查询的话,则很有可能因为数据库性能问题,造成系统响应速度过慢,甚至宕机。那么此时则可以基于Redis进行改造。
@Service
public class GoodsServiceImpl implements GoodsService {
@Autowired
private GoodsMapper goodsMapper;
@Autowired
private RedisTemplate redisTemplate;
@Override
public GoodsEntity findGoodsInfoById(Long goodsId) {
存在redis ,不存在mysql,mysql存在存redis,mysql不存在返回null
GoodsEntity redisGoods = (GoodsEntity) redisTemplate.opsForValue().get("goods:" + goodsId);
if (redisGoods!= null){
return redisGoods;
}
GoodsEntity goodsEntity = goodsMapper.selectById(goodsId);
redisTemplate.opsForValue().set("goods:"+goodsId,goodsEntity);
return goodsEntity;
}
}