百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术教程 > 正文

SpringCache,统一Redis、Memcached操作,轻松将缓存与业务解耦

mhr18 2024-11-10 09:49 17 浏览 0 评论

Spring Cache是Spring实现的一套大统一缓存框架,可以与 Redis、Memcached、Guava、Caffeine这些框架进行耦合。不管底层是Redis还是Memcached,对开发人员来说,都是同一套注解,只是引入的jar依赖不同,比如要试用redis,就引入spring-boot-starter-data-redis。

它利用了AOP,实现了基于注解的缓存功能,并且进行了合理的抽象,业务代码不用关心底层是使用了什么缓存框架,只需要简单地加一个注解,就能实现缓存功能了。而且Spring Cache也提供了很多默认的配置,用户可以3秒钟就使用上一个很不错的缓存功能。

对于现有代码来说,侵入性非常低,只是在需要缓存的地方,增加了Spring Cache的注解。既然有这么好的轮子,干嘛不用呢?

一、Spring Cache 操作Redis

1、Spring Cache 简介

当Spring Boot 结合Redis来作为缓存使用时,最简单的方式就是使用Spring Cache了,使用它我们无需知道Spring中对Redis的各种操作,仅仅通过它提供的@Cacheable 、@CachePut 、@CacheEvict 、@EnableCaching等注解就可以实现缓存功能。

2、常用注解

@EnableCaching

开启缓存功能,一般放在启动类上。

@Cacheable

使用该注解的方法当缓存存在时,会从缓存中获取数据而不执行方法,当缓存不存在时,会执行方法并把返回结果存入缓存中。一般使用在查询方法上,可以设置如下属性:

  • value:缓存名称(必填),指定缓存的命名空间;
  • key:用于设置在命名空间中的缓存key值,可以使用SpEL表达式定义;
  • unless:条件符合则不缓存;
  • condition:条件符合则缓存。

@CachePut

使用该注解的方法每次执行时都会把返回结果存入缓存中。一般使用在新增方法上,可以设置如下属性:

  • value:缓存名称(必填),指定缓存的命名空间;
  • key:用于设置在命名空间中的缓存key值,可以使用SpEL表达式定义;
  • unless:条件符合则不缓存;
  • condition:条件符合则缓存。

@CacheEvict

使用该注解的方法执行时会清空指定的缓存。一般使用在更新或删除方法上,可以设置如下属性:

  • value:缓存名称(必填),指定缓存的命名空间;
  • key:用于设置在命名空间中的缓存key值,可以使用SpEL表达式定义;
  • condition:条件符合则缓存。

3、使用步骤

  • 在pom.xml中添加项目依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
  • 修改配置文件application.yml,添加Redis的连接配置;
spring:
redis:
host: 192.168.1.12 # Redis服务器地址
database: 0 # Redis数据库索引(默认为0)
port: 6379 # Redis服务器连接端口
password: foobared # Redis服务器连接密码(默认为空)
timeout: 1000ms # 连接超时时间


  • 在启动类上添加@EnableCaching注解启动缓存功能;
@EnableCaching
@SpringBootApplication
public class DemoSpringbootRedisApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoSpringbootRedisApplication.class, args);
    }
}
  • 定义PmsBrand类(缓存的对象)
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class PmsBrand{
    private Long id;
    private String brand;
}
  • 接下来在PmsBrandServiceImpl类中使用相关注解来实现缓存功能(缓存的key的值为注解中的value+key,比如"pms_brand_service::pms:brand:100002")

@Service

@Data //lombok Data注解和junit generator冲突,所以导致生成单元测试类失败,生成时需要在对应类中屏蔽掉lombok注解

public class PmsBrandServiceImpl {
    @Data
    @AllArgsConstructor
    public static class PmsBrand implements Serializable {
        private Long id;
        private String brand;
    }


    public static final String SERVICE_KEY = "pms_brand_service";


    // 使用该注解的方法执行时会清空指定的缓存。一般使用在更新或删除方法上
    @CacheEvict(value = PmsBrandServiceImpl.SERVICE_KEY, key = "'pms:brand:'+#id")
    public int update(Long id, PmsBrand brand) {
        brand.setId(id);
        return 1;
    }


    // 使用该注解的方法执行时会清空指定的缓存。一般使用在更新或删除方法上
    @CacheEvict(value = PmsBrandServiceImpl.SERVICE_KEY, key = "'pms:brand:'+#id")
    public int delete(Long id) {
        return 0;
    }


    // 使用该注解的方法每次执行时都会把返回结果存入缓存中。一般使用在新增方法上
    @CachePut(value = PmsBrandServiceImpl.SERVICE_KEY, key = "'pms:brand:'+#id")
    public PmsBrand add(Long id){
        return new PmsBrand(id, "addidas");
    }


    // 使用该注解的方法当缓存存在时,会从缓存中获取数据而不执行方法,当缓存不存在时,会执行方法并把返回结果存入缓存中
    @Cacheable(value = PmsBrandServiceImpl.SERVICE_KEY, key = "'pms:brand:'+#id", unless = "#result==null")
    public PmsBrand getItem(Long id) {
        return new PmsBrand(id, "nike");
    }
}
  • 我们可以调用获取品牌详情的接口测试下效果,此时发现Redis中存储的数据有点像乱码,并且没有设置过期时间;




4、存储JSON格式数据

此时我们就会想到有没有什么办法让Redis中存储的数据变成标准的JSON格式,然后可以设置一定的过期时间,不设置过期时间容易产生很多不必要的缓存数据。

  • 我们可以通过给RedisTemplate设置JSON格式的序列化器,并通过配置RedisCacheConfiguration设置超时时间来实现以上需求,此时别忘了去除启动类上的@EnableCaching注解,具体配置类RedisConfig代码如下;
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {


    /**
     * redis数据库自定义key
     */
    public static final String REDIS_KEY_DATABASE="mall";


    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisSerializer<Object> serializer = redisSerializer();
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(serializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }


    @Bean
    public RedisSerializer<Object> redisSerializer() {
        //创建JSON序列化器
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 此项必须配置,否则会报java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to XXX
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        serializer.setObjectMapper(objectMapper);
        return serializer;
    }


    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        //设置Redis缓存有效期为1天
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer())).entryTtl(Duration.ofDays(1));
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }


}
  • 此时我们再次调用获取商品详情的接口进行测试,会发现Redis中已经缓存了标准的JSON格式数据,并且超时时间被设置为了1天。

【ps,这里有个小问题,使用jackson进行序列化的结果带有@class(这是为了jackson能正常反序列化)】

5、为每一类缓存分别指定过期时间

对前面的redisConfig配置类进行如下更改:

@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
    //设置Redis缓存有效期为1天
    RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer()))
            //默认过期时间
            .entryTtl(Duration.ofDays(1));


    // 针对不同cacheName,设置不同的过期时间,注意这里的brand1hour、brand10minitues对应的就是
    // 缓存注解如@CachePut中的value值,value值相同,则过期时间是一致的
    Map<String, RedisCacheConfiguration> initialCacheConfiguration = new HashMap<String, RedisCacheConfiguration>() {{
        put("brand1hour", RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer())).entryTtl(Duration.ofHours(1))); //1小时
        put("brand10minitues", RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer())).entryTtl(Duration.ofMinutes(10))); // 10分钟
    }};

    return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration, initialCacheConfiguration);
}


6、【常见问题】

1、读取缓存的时候失败,错误提示如下org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Cannot construct instance of `com.example.demospringbootredis.services.PmsBrand` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

解决:根据提示,错误原因是缺少类PmsBrand的构造函数,注意jackson需要的是该类的无参构造函数,所以给对应类加上无参构造函数即可解决该问题。


二、使用Redis连接池

SpringBoot 1.5.x版本Redis客户端默认是Jedis实现的,SpringBoot 2.x版本中默认客户端是用Lettuce实现的,我们先来了解下Jedis和Lettuce客户端。

Jedis vs Lettuce

Jedis在实现上是直连Redis服务,多线程环境下非线程安全,除非使用连接池,为每个 RedisConnection 实例增加物理连接。

Lettuce是一种可伸缩,线程安全,完全非阻塞的Redis客户端,多个线程可以共享一个RedisConnection,它利用Netty NIO框架来高效地管理多个连接,从而提供了异步和同步数据访问方式,用于构建非阻塞的反应性应用程序。

使用步骤

  • 修改application.yml添加Lettuce连接池配置,用于配置线程数量和阻塞等待时间;
spring:
redis:
lettuce:
pool:
max-active: 8 # 连接池最大连接数
max-idle: 8 # 连接池最大空闲连接数
min-idle: 0 # 连接池最小空闲连接数
max-wait: -1ms # 连接池最大阻塞等待时间,负值表示没有限制
  • 由于SpringBoot 2.x中默认并没有使用Redis连接池,所以需要在pom.xml中添加commons-pool2的依赖;
  • <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    </dependency>


    • 如果你没添加以上依赖的话,启动应用的时候就会产生如下错误;
    Caused by: java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig
        at org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration$LettucePoolingClientConfigurationBuilder.<init>(LettucePoolingClientConfiguration.java:84) ~[spring-data-redis-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration.builder(LettucePoolingClientConfiguration.java:48) ~[spring-data-redis-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$PoolBuilderFactory.createBuilder(LettuceConnectionConfiguration.java:149) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
        at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.createBuilder(LettuceConnectionConfiguration.java:107) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
        at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.getLettuceClientConfiguration(LettuceConnectionConfiguration.java:93) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
        at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.redisConnectionFactory(LettuceConnectionConfiguration.java:74) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
        at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$EnhancerBySpringCGLIB$5caa7e47.CGLIB$redisConnectionFactory$0(<generated>) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
        at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$EnhancerBySpringCGLIB$5caa7e47$FastClassBySpringCGLIB$b8ae2813.invoke(<generated>) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
        at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$EnhancerBySpringCGLIB$5caa7e47.redisConnectionFactory(<generated>) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
        ... 111 common frames omitted


    三、自由操作Redis

    Spring Cache 给我们提供了操作Redis缓存的便捷方法,但是也有很多局限性。比如说我们想单独设置一个缓存值的有效期怎么办?我们并不想缓存方法的返回值,我们想缓存方法中产生的中间值怎么办?此时我们就需要用到RedisTemplate这个类了,接下来我们来讲下如何通过RedisTemplate来自由操作Redis中的缓存。

    RedisService

    定义Redis操作业务类,在Redis中有几种数据结构,比如普通结构(对象),Hash结构、Set结构、List结构,该接口中定义了大多数常用操作方法。

    /**
    * redis操作Service
    * Created by macro on 2020/3/3.
    */
    public interface RedisService {
    
    /**
    * 保存属性
    */
    void set(String key, Object value, long time);
    
    /**
    * 保存属性
    */
    void set(String key, Object value);
    
    /**
    * 获取属性
    */
    Object get(String key);
    
    /**
    * 删除属性
    */
    Boolean del(String key);
    
    /**
    * 批量删除属性
    */
    Long del(List<String> keys);
    
    /**
    * 设置过期时间
    */
    Boolean expire(String key, long time);
    
    /**
    * 获取过期时间
    */
    Long getExpire(String key);
    
    /**
    * 判断是否有该属性
    */
    Boolean hasKey(String key);
    
    /**
    * 按delta递增
    */
    Long incr(String key, long delta);
    
    /**
    * 按delta递减
    */
    Long decr(String key, long delta);
    
    /**
    * 获取Hash结构中的属性
    */
    Object hGet(String key, String hashKey);
    
    /**
    * 向Hash结构中放入一个属性
    */
    Boolean hSet(String key, String hashKey, Object value, long time);
    
    /**
    * 向Hash结构中放入一个属性
    */
    void hSet(String key, String hashKey, Object value);
    
    /**
    * 直接获取整个Hash结构
    */
    Map<Object, Object> hGetAll(String key);
    
    /**
    * 直接设置整个Hash结构
    */
    Boolean hSetAll(String key, Map<String, Object> map, long time);
    
    /**
    * 直接设置整个Hash结构
    */
    void hSetAll(String key, Map<String, Object> map);
    
    /**
    * 删除Hash结构中的属性
    */
    void hDel(String key, Object... hashKey);
    
    /**
    * 判断Hash结构中是否有该属性
    */
    Boolean hHasKey(String key, String hashKey);
    
    /**
    * Hash结构中属性递增
    */
    Long hIncr(String key, String hashKey, Long delta);
    
    /**
    * Hash结构中属性递减
    */
    Long hDecr(String key, String hashKey, Long delta);
    
    /**
    * 获取Set结构
    */
    Set<Object> sMembers(String key);
    
    /**
    * 向Set结构中添加属性
    */
    Long sAdd(String key, Object... values);
    
    /**
    * 向Set结构中添加属性
    */
    Long sAdd(String key, long time, Object... values);
    
    /**
    * 是否为Set中的属性
    */
    Boolean sIsMember(String key, Object value);
    
    /**
    * 获取Set结构的长度
    */
    Long sSize(String key);
    
    /**
    * 删除Set结构中的属性
    */
    Long sRemove(String key, Object... values);
    
    /**
    * 获取List结构中的属性
    */
    List<Object> lRange(String key, long start, long end);
    
    /**
    * 获取List结构的长度
    */
    Long lSize(String key);
    
    /**
    * 根据索引获取List中的属性
    */
    Object lIndex(String key, long index);
    
    /**
    * 向List结构中添加属性
    */
    Long lPush(String key, Object value);
    
    /**
    * 向List结构中添加属性
    */
    Long lPush(String key, Object value, long time);
    
    /**
    * 向List结构中批量添加属性
    */
    Long lPushAll(String key, Object... values);
    
    /**
    * 向List结构中批量添加属性
    */
    Long lPushAll(String key, Long time, Object... values);
    
    /**
    * 从List结构中移除属性
    */
    Long lRemove(String key, long count, Object value);
    }


    RedisServiceImpl

    RedisService的实现类,使用RedisTemplate来自由操作Redis中的缓存数据。

    /**
    * redis操作实现类
    * Created by macro on 2020/3/3.
    */
    @Service
    public class RedisServiceImpl implements RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Override
    public void set(String key, Object value, long time) {
    redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }
    
    @Override
    public void set(String key, Object value) {
    redisTemplate.opsForValue().set(key, value);
    }
    
    @Override
    public Object get(String key) {
    return redisTemplate.opsForValue().get(key);
    }
    
    @Override
    public Boolean del(String key) {
    return redisTemplate.delete(key);
    }
    
    @Override
    public Long del(List<String> keys) {
    return redisTemplate.delete(keys);
    }
    
    @Override
    public Boolean expire(String key, long time) {
    return redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }
    
    @Override
    public Long getExpire(String key) {
    return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
    
    @Override
    public Boolean hasKey(String key) {
    return redisTemplate.hasKey(key);
    }
    
    @Override
    public Long incr(String key, long delta) {
    return redisTemplate.opsForValue().increment(key, delta);
    }
    
    @Override
    public Long decr(String key, long delta) {
    return redisTemplate.opsForValue().increment(key, -delta);
    }
    
    @Override
    public Object hGet(String key, String hashKey) {
    return redisTemplate.opsForHash().get(key, hashKey);
    }
    
    @Override
    public Boolean hSet(String key, String hashKey, Object value, long time) {
    redisTemplate.opsForHash().put(key, hashKey, value);
    return expire(key, time);
    }
    
    @Override
    public void hSet(String key, String hashKey, Object value) {
    redisTemplate.opsForHash().put(key, hashKey, value);
    }
    
    @Override
    public Map<Object, Object> hGetAll(String key) {
    return redisTemplate.opsForHash().entries(key);
    }
    
    @Override
    public Boolean hSetAll(String key, Map<String, Object> map, long time) {
    redisTemplate.opsForHash().putAll(key, map);
    return expire(key, time);
    }
    
    @Override
    public void hSetAll(String key, Map<String, Object> map) {
    redisTemplate.opsForHash().putAll(key, map);
    }
    
    @Override
    public void hDel(String key, Object... hashKey) {
    redisTemplate.opsForHash().delete(key, hashKey);
    }
    
    @Override
    public Boolean hHasKey(String key, String hashKey) {
    return redisTemplate.opsForHash().hasKey(key, hashKey);
    }
    
    @Override
    public Long hIncr(String key, String hashKey, Long delta) {
    return redisTemplate.opsForHash().increment(key, hashKey, delta);
    }
    
    @Override
    public Long hDecr(String key, String hashKey, Long delta) {
    return redisTemplate.opsForHash().increment(key, hashKey, -delta);
    }
    
    @Override
    public Set<Object> sMembers(String key) {
    return redisTemplate.opsForSet().members(key);
    }
    
    @Override
    public Long sAdd(String key, Object... values) {
    return redisTemplate.opsForSet().add(key, values);
    }
    
    @Override
    public Long sAdd(String key, long time, Object... values) {
    Long count = redisTemplate.opsForSet().add(key, values);
    expire(key, time);
    return count;
    }
    
    @Override
    public Boolean sIsMember(String key, Object value) {
    return redisTemplate.opsForSet().isMember(key, value);
    }
    
    @Override
    public Long sSize(String key) {
    return redisTemplate.opsForSet().size(key);
    }
    
    @Override
    public Long sRemove(String key, Object... values) {
    return redisTemplate.opsForSet().remove(key, values);
    }
    
    @Override
    public List<Object> lRange(String key, long start, long end) {
    return redisTemplate.opsForList().range(key, start, end);
    }
    
    @Override
    public Long lSize(String key) {
    return redisTemplate.opsForList().size(key);
    }
    
    @Override
    public Object lIndex(String key, long index) {
    return redisTemplate.opsForList().index(key, index);
    }
    
    @Override
    public Long lPush(String key, Object value) {
    return redisTemplate.opsForList().rightPush(key, value);
    }
    
    @Override
    public Long lPush(String key, Object value, long time) {
    Long index = redisTemplate.opsForList().rightPush(key, value);
    expire(key, time);
    return index;
    }
    
    @Override
    public Long lPushAll(String key, Object... values) {
    return redisTemplate.opsForList().rightPushAll(key, values);
    }
    
    @Override
    public Long lPushAll(String key, Long time, Object... values) {
    Long count = redisTemplate.opsForList().rightPushAll(key, values);
    expire(key, time);
    return count;
    }
    
    @Override
    public Long lRemove(String key, long count, Object value) {
    return redisTemplate.opsForList().remove(key, count, value);
    }
    }


    RedisController

    测试RedisService中缓存操作的Controller,大家可以调用测试下。

    /**
    * Redis测试Controller
    * Created by macro on 2020/3/3.
    */
    @Api(tags = "RedisController", description = "Redis测试")
    @Controller
    @RequestMapping("/redis")
    public class RedisController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private PmsBrandService brandService;
    
    @ApiOperation("测试简单缓存")
    @RequestMapping(value = "/simpleTest", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<PmsBrand> simpleTest() {
    List<PmsBrand> brandList = brandService.list(1, 5);
    PmsBrand brand = brandList.get(0);
    String key = "redis:simple:" + brand.getId();
    redisService.set(key, brand);
    PmsBrand cacheBrand = (PmsBrand) redisService.get(key);
    return CommonResult.success(cacheBrand);
    }
    
    @ApiOperation("测试Hash结构的缓存")
    @RequestMapping(value = "/hashTest", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<PmsBrand> hashTest() {
    List<PmsBrand> brandList = brandService.list(1, 5);
    PmsBrand brand = brandList.get(0);
    String key = "redis:hash:" + brand.getId();
    Map<String, Object> value = BeanUtil.beanToMap(brand);
    redisService.hSetAll(key, value);
    Map<Object, Object> cacheValue = redisService.hGetAll(key);
    PmsBrand cacheBrand = BeanUtil.mapToBean(cacheValue, PmsBrand.class, true);
    return CommonResult.success(cacheBrand);
    }
    
    @ApiOperation("测试Set结构的缓存")
    @RequestMapping(value = "/setTest", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Set<Object>> setTest() {
    List<PmsBrand> brandList = brandService.list(1, 5);
    String key = "redis:set:all";
    redisService.sAdd(key, (Object[]) ArrayUtil.toArray(brandList, PmsBrand.class));
    redisService.sRemove(key, brandList.get(0));
    Set<Object> cachedBrandList = redisService.sMembers(key);
    return CommonResult.success(cachedBrandList);
    }
    
    @ApiOperation("测试List结构的缓存")
    @RequestMapping(value = "/listTest", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<Object>> listTest() {
    List<PmsBrand> brandList = brandService.list(1, 5);
    String key = "redis:list:all";
    redisService.lPushAll(key, (Object[]) ArrayUtil.toArray(brandList, PmsBrand.class));
    redisService.lRemove(key, 1, brandList.get(0));
    List<Object> cachedBrandList = redisService.lRange(key, 0, 3);
    return CommonResult.success(cachedBrandList);
    }
    }

    相关推荐

    Redis合集-使用benchmark性能测试

    采用开源Redis的redis-benchmark工具进行压测,它是Redis官方的性能测试工具,可以有效地测试Redis服务的性能。本次测试使用Redis官方最新的代码进行编译,详情请参见Redis...

    Java简历总被已读不回?面试挂到怀疑人生?这几点你可能真没做好

    最近看了几十份简历,发现大部分人不是技术差,而是不会“卖自己”——一、简历死穴:你写的不是经验,是岗位说明书!反面教材:ד使用SpringBoot开发项目”ד负责用户模块功能实现”救命写法:...

    redission YYDS(redission官网)

    每天分享一个架构知识Redission是一个基于Redis的分布式Java锁框架,它提供了各种锁实现,包括可重入锁、公平锁、读写锁等。使用Redission可以方便地实现分布式锁。red...

    从数据库行锁到分布式事务:电商库存防超卖的九重劫难与破局之道

    2023年6月18日我们维护的电商平台在零点刚过3秒就遭遇了严重事故。监控大屏显示某爆款手机SKU_IPHONE13_PRO_MAX在库存仅剩500台时,订单系统却产生了1200笔有效订单。事故复盘发...

    SpringBoot系列——实战11:接口幂等性的形而上思...

    欢迎关注、点赞、收藏。幂等性不仅是一种技术需求,更是数字文明对确定性追求的体现。在充满不确定性的网络世界中,它为我们建立起可依赖的存在秩序,这或许正是技术哲学最深刻的价值所在。幂等性的本质困境在支付系...

    如何优化系统架构设计缓解流量压力提升并发性能?Java实战分享

    如何优化系统架构设计缓解流量压力提升并发性能?Java实战分享在高流量场景下。首先,我需要回忆一下常见的优化策略,比如负载均衡、缓存、数据库优化、微服务拆分这些。不过,可能还需要考虑用户的具体情况,比...

    Java面试题: 项目开发中的有哪些成长?该如何回答

    在Java面试中,当被问到“项目中的成长点”时,面试官不仅想了解你的技术能力,更希望看到你的问题解决能力、学习迭代意识以及对项目的深度思考。以下是回答的策略和示例,帮助你清晰、有说服力地展示成长点:一...

    互联网大厂后端必看!Spring Boot 如何实现高并发抢券逻辑?

    你有没有遇到过这样的情况?在电商大促时,系统上线了抢券活动,结果活动刚一开始,服务器就不堪重负,出现超卖、系统崩溃等问题。又或者用户疯狂点击抢券按钮,最后却被告知无券可抢,体验极差。作为互联网大厂的后...

    每日一题 |10W QPS高并发限流方案设计(含真实代码)

    面试场景还原面试官:“如果系统要承载10WQPS的高并发流量,你会如何设计限流方案?”你:“(稳住,我要从限流算法到分布式架构全盘分析)…”一、为什么需要限流?核心矛盾:系统资源(CPU/内存/数据...

    Java面试题:服务雪崩如何解决?90%人栽了

    服务雪崩是指微服务架构中,由于某个服务出现故障,导致故障在服务之间不断传递和扩散,最终造成整个系统崩溃的现象。以下是一些解决服务雪崩问题的常见方法:限流限制请求速率:通过限流算法(如令牌桶算法、漏桶算...

    面试题官:高并发经验有吗,并发量多少,如何回复?

    一、有实际高并发经验(建议结构)直接量化"在XX项目中,系统日活用户约XX万,核心接口峰值QPS达到XX,TPS处理能力为XX/秒。通过压力测试验证过XX并发线程下的稳定性。"技术方案...

    瞬时流量高并发“保命指南”:这样做系统稳如泰山,老板跪求加薪

    “系统崩了,用户骂了,年终奖飞了!”——这是多少程序员在瞬时大流量下的真实噩梦?双11秒杀、春运抢票、直播带货……每秒百万请求的冲击,你的代码扛得住吗?2025年了,为什么你的系统一遇高并发就“躺平”...

    其实很多Java工程师不是能力不够,是没找到展示自己的正确姿势。

    其实很多Java工程师不是能力不够,是没找到展示自己的正确姿势。比如上周有个小伙伴找我,五年经验但简历全是'参与系统设计''优化接口性能'这种空话。我就问他:你做的秒杀...

    PHP技能评测(php等级考试)

    公司出了一些自我评测的PHP题目,现将题目和答案记录于此,以方便记忆。1.魔术函数有哪些,分别在什么时候调用?__construct(),类的构造函数__destruct(),类的析构函数__cal...

    你的简历在HR眼里是青铜还是王者?

    你的简历在HR眼里是青铜还是王者?兄弟,简历投了100份没反应?面试总在第三轮被刷?别急着怀疑人生,你可能只是踩了这些"隐形求职雷"。帮3630+程序员改简历+面试指导和处理空窗期时间...

    取消回复欢迎 发表评论: