redis Spring esay way

本文介绍如何在Spring框架中使用Redis进行数据缓存。通过配置CacheManager及使用@Cacheable等注解,可以有效地提高应用性能。文章还探讨了自定义Key生成器的方法。

Caching Data in Spring Using Redis

18 Dec 2014 · By Casey Scarborough

Caching is a way for applications to store data so that future requests to the same data are returned faster and do not require repeating computationally expensive operations. The Spring Frameworkprovides a simple way to cache the results of method calls with little to no configuration.

The examples in this post use Spring 4.1.3 and Spring Data Redis 1.4.1, the latest versions at the time of this writing. Full source code for this post can be found here.

Installing Dependencies

You'll need to install the spring-data-redis and jedis plugins. Add the following to your pom.xml file in your Spring project if you're using Maven:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.4.1.RELEASE</version>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.6.1</version>
</dependency>

If you're using Gradle, you can add the following to your build.gradle file:

compile "org.springframework.data:spring-data-redis:1.4.1.RELEASE"
compile "redis.clients:jedis:2.6.1"

Enabling Cache Support in Your Spring Application

To enable support for caching in your application, you'll want to create a new CacheManager bean. There are many different implementations of the CacheManager interface, but for this post we'll be usingRedisCacheManager to allow integration with Redis.

Java-based Configuration

If you're using Java-based configuration, you'll want to annotate one of your configuration classes with the @EnableCaching annotation and expose a CacheManager bean. You'll also need a connection factory and a RedisTemplate bean for Spring to communicate with your Redis database. An exampleCacheConfig class is shown below:

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

  @Bean
  public JedisConnectionFactory redisConnectionFactory() {
    JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();

    // Defaults
    redisConnectionFactory.setHostName("127.0.0.1");
    redisConnectionFactory.setPort(6379);
    return redisConnectionFactory;
  }

  @Bean
  public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
    RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
    redisTemplate.setConnectionFactory(cf);
    return redisTemplate;
  }

  @Bean
  public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);

    // Number of seconds before expiration. Defaults to unlimited (0)
    cacheManager.setDefaultExpiration(300);
    return cacheManager;
  }
}

Caching the Results of a Method

After setting up your caching configuration, you can then begin to start caching method results with the@Cacheable annotation. Putting this annotation on a method will cause it's results to be cached in your Redis database for the length specified in your expiration, or until it is manually expired.

See the following example:

import org.apache.log4j.Logger;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ExampleController {

  private static final Logger log = Logger.getLogger(ExampleController.class);

  @RequestMapping(value = "/", method = RequestMethod.GET)
  @ResponseBody
  @Cacheable("calculateResult")
  public String calculateResult() {
    log.debug("Performing expensive calculation...");
    // perform computationally expensive calculation
    return "result";
  }
}

Executing this method multiple times causes only one log output:

2014-12-18 19:24:30 DEBUG ExampleController:19 - Performing expensive calculation...

And you can see the cached item in your Redis instance:

Updating and Evicting Cached Data

In addition to the @Cacheable annotation, Spring provides the @CachePut and @CacheEvict annotations for manually managing cached data. The @CachePut annotation allows you to update the cache without interfering with the execution of the method. For example, if you updated a user, you would want to place the result into the cache to be looked up later:

@CachePut(value = 'user', key = "#id")
public User updateUser(Long id, UserDescriptor descriptor)

This method will always be executed and its results stored in your cache.

On the other hand, there will be times where you will want to 'evict' data from your cache, that is, to remove it. For example, when deleting a user:

@CacheEvict(value = 'user', key = "#id")
public void deleteUser(Long id)

Implementing a Custom Key Generator

For basic purposes, the default key generation system for cached data works. The parameters to your method become the key in your cache store. For example, in the following method, the value for the parameter username would become the key in your store:

@Cacheable("users")
public User findByUsername(String username)

But this becomes problematic when you want cache the result of another method that also takes in the same value, for instance:

@Cacheable("users")
public Integer getLoginCountByUsername(String username)

You could easily just specify a different key for each @Cacheable annotation, but that becomes tedious and hard to maintain. The solution is to implement a custom key generator that will generate the key for each method to be unique by default. Adding a keyGenerator bean to your CacheConfig class (shown above) will give you this functionality. Note that for your custom key generator to work by default, this class must implement the CachingConfigurer interface. Extending CachingConfigurerSupport will provide this for you.

// Previous imports omitted
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;

import java.lang.reflect.Method;

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

  // Previous methods omitted

  @Bean
  public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
      @Override
      public Object generate(Object o, Method method, Object... objects) {
        // This will generate a unique key of the class name, the method name,
        // and all method parameters appended.
        StringBuilder sb = new StringBuilder();
        sb.append(o.getClass().getName());
        sb.append(method.getName());
        for (Object obj : objects) {
          sb.append(obj.toString());
        }
        return sb.toString();
      }
    };
  }
}

Now when your method results are cached, they will be cached with your custom key generator implementation.

Conclusion

This is a simple example of how to cache application data in your Redis instance. Although this post focuses on caching with Redis, caching with other providers is very straightforward and the caching concepts remain the same. For more information and complete documentation, see Spring's caching reference. Feel free to leave a comment if you have any questions or run into any problems.

内容概要:本文档是一份关于交换路由配置的学习笔记,系统地介绍了网络设备的远程管理、交换机与路由器的核心配置技术。内容涵盖Telnet、SSH、Console三种远程控制方式的配置方法;详细讲解了VLAN划分原理及Access、Trunk、Hybrid端口的工作机制,以及端口镜像、端口汇聚、端口隔离等交换技术;深入解析了STP、MSTP、RSTP生成树协议的作用与配置步骤;在路由部分,涵盖了IP地址配置、DHCP服务部署(接口池与全局池)、NAT转换(静态与动态)、静态路由、RIP与OSPF动态路由协议的配置,并介绍了策略路由和ACL访问控制列表的应用;最后简要说明了华为防火墙的安全区域划分与基本安全策略配置。; 适合人群:具备一定网络基础知识,从事网络工程、运维或相关技术岗位1-3年的技术人员,以及准备参加HCIA/CCNA等认证考试的学习者。; 使用场景及目标:①掌握企业网络中常见的交换与路由配置技能,提升实际操作能力;②理解VLAN、STP、OSPF、NAT、ACL等核心技术原理并能独立完成中小型网络搭建与调试;③通过命令示例熟悉华为设备CLI配置逻辑,为项目实施和故障排查提供参考。; 阅读建议:此笔记以实用配置为主,建议结合模拟器(如eNSP或Packet Tracer)动手实践每一条命令,对照拓扑理解数据流向,重点关注VLAN间通信、路由选择机制、安全策略控制等关键环节,并注意不同设备型号间的命令差异。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值