标签:map desktop 代码 apach eid string ase TE temp
参考:https://www.cnblogs.com/LQBlog/p/9214517.html
1.添加pom依赖
<!-- Spring Boot Reids 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>1.5.7.RELEASE</version> </dependency> <!--spring2.0集成redis所需common-pool2--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.4.2</version> </dependency>
2.application.properties配置redis连接信息
spring
redis:
host: 192.168.65.128
port: 6379
timeout: 0
password: # 密码 没有则不填
3.添加测试代码
@Service public class AddressServiceImpl extends BaseServiceImpl<Address> implements AddressService { @Resource AddressMapper addressMapper; @Autowired private RedisTemplate<Object,Object> redisTemplate; @Override public Address selectByPrimaryKey(Object key) { String redisKey=key.toString(); Address address=(Address) redisTemplate.opsForValue().get(redisKey); if(address==null){ //防止缓存穿透 synchronized (this) { address = (Address) redisTemplate.opsForValue().get(redisKey); if (address == null) { address = super.selectByPrimaryKey(key); redisTemplate.opsForValue().set(redisKey, address); } } }else { System.out.println("使用缓存了"); } return address; } }
红色代码是为了防止内存穿透,比如你这个业务方法有10000个人同时访问,如果不加锁。当第一次访问都判断address为空 然后全部去查数据库,正常应该是一个连接查询数据库并设置缓存 后面9999都使用缓存
通过redis Desktop Manager查看结果
因默认key 和value都是用jdk自带的序列化方式JdkSerializationRedisSerializer 可以发现可读性很差
新增一个redisConfig 配置序列化方式
@Configuration public class RedisConfig { /** * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类 * @param redisConnectionFactory * @return */ @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // 使用Jackson2JsonRedisSerialize 替换默认序列化 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); // 设置value的序列化规则和 key的序列化规则 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
再次测试结果
标签:map desktop 代码 apach eid string ase TE temp
原文地址:https://www.cnblogs.com/LQBlog/p/9242750.html