Spring Boot 系列 | 第五篇:使用Redis

Spring Boot 系列 | 第五篇:使用Redis

前言

本篇介绍如何在Spring Boot中使用Redis

准备工作

需要准备一下东西:

  • 一个Spring Boot项目
  • 本机安装好Redis服务器

本篇目录如下:

  • Spring Boot集成Redis
  • Redis的三种加载配置方式
  • 使用Redis并进行测试
  • 使用Redis缓存

SpringBoot集成Redis

添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.properties配置:

spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
# 连接超时时间 单位 ms(毫秒)
spring.redis.timeout=3000

# 连接池中的最大空闲连接,默认值也是8。
spring.redis.pool.max-idle=8
#连接池中的最小空闲连接,默认值也是0。
spring.redis.pool.min-idle=0
# 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
spring.redis.pool.max-active=8
# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException
spring.redis.pool.max-wait=-1

#################redis哨兵设置#################
# Redis服务器master的名字
#spring.redis.sentinel.master=master8026
# redis-sentinel的配置地址和端口
#spring.redis.sentinel.nodes=10.189.80.25:26379,10.189.80.26:26379,10.189.80.27:26378

Redis的三种加载配置方式

Spring Boot中共有三种加载Redis配置的方式:

  • AutoConfig加载
  • 自己写代码加载
  • xml加载
AutoConfig加载

因为上面依赖了spring-boot-starter-data-redis,可以使用默认的RedisAutoConfiguration类加载properties文件的配置。

打开RedisAutoConfiguration可以看到自动帮我们注入了两个bean:

/**
 * Standard Redis configuration.
 */
@Configuration
protected static class RedisConfiguration {

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(
            RedisConnectionFactory redisConnectionFactory)
                    throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
                    throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

此种方式会默认加载applicaiton中的redis配置,提供了以下两种bean

  • RedisTemplate<Object,Object> 可以对Rediskeyvalue都为object类型的数据进行操作,默认会将对象使用JdkSerializationRedisSerializer进行序列化
  • StringRedisTemplate可以对Rediskeyvalue都是String类型的数据进行操作
自己写代码配置
@Configuration
public class RedisConfig{

  private Logger logger = LoggerFactory.getLogger(this.getClass());

  @Value("${spring.redis.host}")
  private String host;

  @Value("${spring.redis.port}")
  private int port;

  @Value("${spring.redis.timeout}")
  private int timeout;

  @Value("${spring.redis.password}")
  private String password;

  @Value("${spring.redis.database}")
  private int database;

  @Value("${spring.redis.pool.max-idle}")
  private int maxIdle;

  @Value("${spring.redis.pool.min-idle}") 
  private int minIdle;

  /**
   * redis模板,存储关键字是字符串,值是Jdk序列化
   * @Description:
   * @param factory
   * @return
   */
  @Bean
  public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory) {
      RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
      redisTemplate.setConnectionFactory(factory);
      RedisSerializer<String> redisSerializer = new StringRedisSerializer();
      redisTemplate.setKeySerializer(redisSerializer);
      redisTemplate.setHashKeySerializer(redisSerializer);
      //JdkSerializationRedisSerializer序列化方式;
      JdkSerializationRedisSerializer jdkRedisSerializer=new JdkSerializationRedisSerializer();
      redisTemplate.setValueSerializer(jdkRedisSerializer);
      redisTemplate.setHashValueSerializer(jdkRedisSerializer);
      redisTemplate.afterPropertiesSet();
      return redisTemplate; 
  }
}
XML方式配置

在程序入口添加如下代码:

@ImportResource(locations={"classpath:spring-redis.xml"}) 

resource文件夹下新建文件spring-redis.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/cache 
     http://www.springframework.org/schema/cache/spring-cache.xsd
        http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="minIdle" value="${redis.pool.minIdle}" />
        <property name="maxIdle" value="${redis.pool.maxIdle}" />
        <property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
    </bean>

    <bean id="jedisConnectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="usePool" value="true"></property>
        <property name="hostName" value="${redis.ip}" />
        <property name="port" value="${redis.port}" />
        <property name="password" value="${redis.password}" />
        <property name="timeout" value="${redis.timeout}" />
        <property name="database" value="${redis.default.db}"></property>
        <constructor-arg ref="jedisPoolConfig" />
    </bean>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
        <property name="KeySerializer">
            <bean
                class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
        </property>
        <property name="ValueSerializer">
            <bean
                class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"></bean>
        </property>
        <property name="HashKeySerializer">
            <bean
                class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
        </property>
        <property name="HashValueSerializer">
            <bean
                class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"></bean>
        </property>
    </bean>
</beans>

使用Redis并进行测试

这里我们使用自动配置的方式(添加依赖即可,不需要其他配置)

@Repository
public class RedisService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public void add(String key, User user, Long time) {
        Gson gson = new Gson();
        stringRedisTemplate.opsForValue().set(key, gson.toJson(user), time, TimeUnit.MINUTES);
    }

    public void add(String key, List<User> users, Long time) {
        Gson gson = new Gson();
        String src = gson.toJson(users);
        stringRedisTemplate.opsForValue().set(key, src, time, TimeUnit.MINUTES);
    }

    public User get(String key) {
        String source = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(source)) {
            return new Gson().fromJson(source, User.class);
        }
        return null;
    }

    public List<User> getUserList(String key) {
        String source = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(source)) {
            return new Gson().fromJson(source, new TypeToken<List<User>>() {
            }.getType());
        }
        return null;
    }

    public void delete(String key) {
        stringRedisTemplate.opsForValue().getOperations().delete(key);
    }
}

test下编写测试文件:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RedisTest {

    @Autowired
    RedisService redisService;

    @Before
    public void setUp() {

    }

    @Test
    public void get() {
        User user = new User();
        user.setName("wangjianfeng");
        user.setAge(22);
        redisService.add("userByName:" + user.getName(), user, 10L);
        List<User> list = new ArrayList<>();
        list.add(user);
        redisService.add("list", list, 10L);
        User user1 = redisService.get("userByName:wangjianfeng");
        Assert.notNull(user1, "user is null");
        List<User> list2 = redisService.getUserList("list");
        Assert.notNull(list2, "list is null");
    }
}

测试通过。

使用Redis缓存

上面内容了解了Redis的基本存取使用,这里介绍Spring使用Redis缓存。

本节内容有部分参考了:Spring Boot 使用Redis缓存

缓存存储

Spring提供了很多缓存管理器,例如

  • SimpleCacheManager
  • EhCacheManager
  • CaffeineCacheManager
  • GuavaCacheManager
  • CompositeCacheManager

Spring Boot中除了核心的Spring缓存之外,Spring Data还提供了缓存管理器:RedisCacheManager

Spring Boot中通过@EnableCaching注解自动化配置适合的缓存管理器。

所以在程序入口问题加入:@EnableCaching注解

@SpringBootApplication
@EnableCaching
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

然后我们使用自己写代码配置的方式,修改RedisConfig添加@EnableCaching注解,并继承CachingCongigurerSupport

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
    ...
}

Spring提供了如下注解来声明缓存规则

注解描述
@Cacheable表明在Spring调用之前,首先应该在缓存中查找方法的返回值,如果这个值能够找到,就会返回缓存的值,否则这个方法会被调用,返回值会放到缓存中
@CachePut表明Spring应该将该方法返回值放到缓存中,在方法调用前不会检查缓存,方法始终会被调用
@CacheEvict表明Spring应该在缓存中清楚一个或多个条目
@Caching分组注解,能够同时应用多个其他的缓存注解
@CacheConfig可以在类层级配置一些共有的缓存配置

@Cacheable@CachePut有一些共有的属性:

属性类型描述
valueString[]缓存名称
conditionSpEL表达式,如果得到的值是false,则不会应用缓存在该方法
keyStringSpEl表达式,用来计算自定义的缓存key
unlessStringSpEl表达式,如果得到的值为true,返回值不会放到缓存中

在一个请求方法上加上@Cacheable注解,测试效果:

 @Cacheable(value = "testCache")
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Integer id) {
        return userService.findUser(id);
    }

访问这个接口后报错:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at org.springframework.data.redis.serializer.StringRedisSerializer.serialize(StringRedisSerializer.java:33)
at org.springframework.data.redis.cache.RedisCacheKey.serializeKeyElement(RedisCacheKey.java:74)
at org.springframework.data.redis.cache.RedisCacheKey.getKeyBytes(RedisCacheKey.java:49)
at org.springframework.data.redis.cache.RedisCache$1.doInRedis(RedisCache.java:176)
at org.springframework.data.redis.cache.RedisCache$1.doInRedis(RedisCache.java:172)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:207)

原因如下:
Redis缓存的key生成策略:

If no params are given,return SimpleKey.EMPTY.
If only one params is given,return that instance.
If more the one param is given,return a SimpleKey containing all parameters.

从上面的策略可以看出,上面缓存testCache中使用的key是整形的id参数,但是在设置RedisTemplate的时候设置了template.setKeySerializer(new StringRedisSerializer());所以导致类型转换错误,所以需要重写keyGenerator定制key的生成策略

修改RedisConfig类,添加keyGenerator的方法:

@Bean
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
        @Override
        public Object generate(Object target, Method method, Object... params) {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName())
                    .append(":")
                    .append(method.getName());
            for (Object obj : params) {
                sb.append(":")
                        .append(obj.toString());
            }
            return sb.toString();
        }
    };
}

这里的策略很简单,使用类名 + 方法名 + 参数作为缓存key。

再次访问两次这个接口:

http://localhost:8080/demo/users/3
http://localhost:8080/demo/users/4

查看Redis内容:

127.0.0.1:6379> keys *
1) "testCache~keys"
2) "com.example.demo.controller.UserController:getUserById:3"
3) "com.example.demo.controller.UserController:getUserById:4"
127.0.0.1:6379> get com.example.demo.controller.UserController:getUserById:3
"[\"com.example.demo.model.User\",{\"id\":3,\"name\":\"\xe7\x8e\x8b\xe5\x89\x91\xe9\x94\x8b\",\"age\":12}]"
127.0.0.1:6379> zrange testCache~keys 0 10
1) "com.example.demo.controller.UserController:getUserById:3"
2) "com.example.demo.controller.UserController:getUserById:4"
127.0.0.1:6379>

可以看到Redis里面保存了一下内容:

  • 两条String类型的键值对,key就是生成的keyvalue就是user对象序列化之后的结果。
  • 一个有序集合。其中key@Cacheable中的value + ~keys.内容为String类型的键值对的key.
缓存更新与删除

更新和删除缓存使用到@CachePut@CacheEvict。这时候发现用原来的key生成策略无法保证增删查改的key一致(因为参数不同,方法名也不同),所以需要修改一下KeyGenerator,改为缓存key按照 缓存名称 + id的方式

@Bean
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
        @Override
        public Object generate(Object target, Method method, Object... params) {
            StringBuilder sb = new StringBuilder();
            String[] value = new String[1];
            Cacheable cacheable = method.getAnnotation(Cacheable.class);
            if (cacheable != null) {
                value = cacheable.value();
            }
            CachePut cachePut = method.getAnnotation(CachePut.class);
            if (cachePut != null) {
                value = cachePut.value();
            }
            CacheEvict cacheEvict = method.getAnnotation(CacheEvict.class);
            if (cacheEvict != null) {
                value = cacheEvict.value();
            }
            sb.append(value[0]);
            for (Object obj : params) {
                sb.append(":")
                        .append(obj.toString());
            }
            return sb.toString();
        }
    };
}

然后修改Controller

@Cacheable(value = "user")
@GetMapping("/{id}")
public User getUserById(@PathVariable Integer id) {
    return userService.findUser(id);
}

@CachePut(value = "user", key = "#root.caches[0].name + ':' + #user.id")
@PostMapping("/")
public User addUser(User user) {
    userService.add(user);
    //返回增加后的id
    return user;
}

//#root.caches[0].name:当前被调用方法所使用的Cache, 即"user"
@CachePut(value = "user", key = "#root.caches[0].name + ':' + #user.id")
@PutMapping("/{id}")
public User updateUser(@PathVariable Integer id, User user) {
    user.setId(id);
    userService.update(user);
    return user;
}

@CacheEvict(value = "user")
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Integer id) {
    int result = userService.delete(id);
    return result == 1 ? "删除成功" : "删除失败";
}

如果@CachePut指定了key属性之后,则不会再调用keygenerator的方法。此时可以看到,增删查改的方法缓存的key都是user:id这样的格式。

然后进行测试,测试过程为测试某个方法然后到redis中查看缓存是否正确。

下面贴出所有相关的代码:

RedisConfig.java

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        // 设置缓存过期时间,秒
        rcm.setDefaultExpiration(60 * 10);
        return rcm;
    }

    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                String[] value = new String[1];
                Cacheable cacheable = method.getAnnotation(Cacheable.class);
                if (cacheable != null) {
                    value = cacheable.value();
                }
                CachePut cachePut = method.getAnnotation(CachePut.class);
                if (cachePut != null) {
                    value = cachePut.value();
                }
                CacheEvict cacheEvict = method.getAnnotation(CacheEvict.class);
                if (cacheEvict != null) {
                    value = cacheEvict.value();
                }
                sb.append(value[0]);
                for (Object obj : params) {
                    sb.append(":")
                            .append(obj.toString());
                }
                return sb.toString();
            }
        };
    }


    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        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);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}

UserController.java

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping(value = "/")
    public List<User> getUsers() {
        return userService.findUsers();
    }

    @Cacheable(value = "user")
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Integer id) {
        return userService.findUser(id);
    }

    @CachePut(value = "user", key = "#root.caches[0].name + ':' + #user.id")
    @PostMapping("/")
    public User addUser(User user) {
        userService.add(user);
        //返回增加后的id
        return user;
    }

    //#root.caches[0].name:当前被调用方法所使用的Cache, 即"user"
    @CachePut(value = "user", key = "#root.caches[0].name + ':' + #user.id")
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Integer id, User user) {
        user.setId(id);
        userService.update(user);
        return user;
    }

    @CacheEvict(value = "user")
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Integer id) {
        int result = userService.delete(id);
        return result == 1 ? "删除成功" : "删除失败";
    }
}
  • 7
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值