spring+redis整合

来源:互联网 发布:淘宝买手店 编辑:程序博客网 时间:2024/05/29 09:08

本文实现spring+redis缓存服务器的整合。


1、windows下redis安装

(1)、下载

由于本文出于测试目的,因此使用windows的redis版本。从https://github.com/ServiceStack/redis-windows下载redis,下载后解压,找到解压文件夹中的downloads中的redis-latest.zip压缩包,该压缩包就是当前支持的最新的windiws版本(这里需要注意了,好似只是支持64位的系统,而且需要使用Administrator的管理员用户名登陆才能运行),解压该压缩包得到redis的资源文件。

(2)、创建启动脚本

创建一个bat脚本,本文中卫startup.bat脚本,然后在其中输入如下启动redis服务器的命令:

redis-server.exe  redis.windows.conf

(3)、启动redis服务器

双击启动脚本即可启动服务器。启动后如下:

关闭该命令行窗口即可关闭redis服务器。

(4)、测试

双击运行解压目录下的redis-cli.exe程序,正常运行后会弹出客户端测试框,输入如下命令进行简单测试

set hello 123get hello
如图

(5)、配置redis密码

先关闭redis服务器,然后编辑redis.windows.conf文件,搜索requirepass配置,去掉前面的注释符号(#)。保存并关闭,此时redis的默认密码就是requirepass后面的值,本文为foobared。

(6)、使用密码登陆测试

首先运行脚本启动redis服务器,然后在redis-cli.exe所在目录下安装shift键,点击鼠标邮件选择"在此处打开命令窗口"。输入如下命令登陆redis服务器进行测试:

redis-cli.exe -h 127.0.0.1 -p 6379 -a foobared
登陆成功后按照之前的测试步骤进行redis测试即可。

2、linux下的redis安装和配置

linux下的redis安装和配置可以参考如下博客:http://blog.csdn.net/smilefyx/article/details/73822851

3、spring+redis整合测试

(1)、依赖导入

创建一个maven工程,导入必要的spring和其他相关依赖jar包,然后导入如下redis相关的jar包:

<dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>1.6.0.RELEASE</version></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.7.3</version></dependency>

(2)、创建java配置类

本文使用的是基于java的配置类,配置类中主要是配置redis的连接工厂,redis的模板操作类、cacheManager和一个简单的测试bean。代码如下:

package cn.hi_fei.redis.configuration;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;import cn.hi_fei.redis.impl.CacheServiceImpl;@Configuration@EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport{    @Bean      public RedisConnectionFactory 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<String, String> redisTemplate) {          RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);           // Number of seconds before expiration. Defaults to unlimited (0)          cacheManager.setDefaultExpiration(3000); // Sets the default expire time (in seconds)          return cacheManager;      }          @Bean("CacheServiceImpl")    public CacheServiceImpl getCacheServiceImpl() {    return new CacheServiceImpl();    }}

(3)、测试代码

首先创建一个用于加载配置的基类,该类用于加载配置。源码如下

package cn.hi_fei.redis;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import cn.hi_fei.redis.configuration.RedisCacheConfig;@RunWith(SpringJUnit4ClassRunner.class)  @ContextConfiguration(classes = {RedisCacheConfig.class})   public class BaseTest {}

第二步创建一个使用spring缓存相关注解的测试服务类,用于在测试用例中自动注入用来测试spring的注解。代码如下:

package cn.hi_fei.redis.impl;import org.apache.log4j.Logger;import org.springframework.cache.annotation.Cacheable;public class CacheServiceImpl {Logger logger = Logger.getLogger(CacheServiceImpl.class);@Cacheable(value="test",key="#key")public String hello(String key) {logger.info("Get without cache.");return "Hello!";}}

第三部创建继承于第一步的基类的实体测试类,用于测试redis和spring的配合使用。本例中使用两种方式用于测试redis。第一种是基于spring注解的实现,第二种是基于spring都redis操作的模板类实现。源代码如下:

package cn.hi_fei.redis.impl;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import org.apache.log4j.Logger;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.data.redis.core.RedisTemplate;import cn.hi_fei.redis.BaseTest;public class CacheTest extends BaseTest{Logger logger = Logger.getLogger(CacheTest.class);@Autowiredprivate RedisTemplate<String, String> redis;@Autowired@Qualifier("CacheServiceImpl")private CacheServiceImpl mService;@Testpublic void test() {//1logger.info("1="+this.mService.hello("hello3"));        logger.info("2="+this.mService.hello("hello3"));        try {    logger.info("Wait input to exit.");            InputStreamReader is_reader = new InputStreamReader(System.in);          new BufferedReader(is_reader).readLine();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}        //2logger.info("1="+this.hello("hello4"));        logger.info("2="+this.hello("hello4"));        try {    logger.info("Wait input to exit.");            InputStreamReader is_reader = new InputStreamReader(System.in);          new BufferedReader(is_reader).readLine();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}        }public String hello(String key) {String v = redis.opsForValue().get(key);if(null != v) {logger.info("Get from cache.");return v;}logger.info("Get without cache.");redis.opsForValue().set(key, "Hello!");return "Hello!";}}

运行后的测试结果如下:

(4)、代码下载

本例的源码工程可以从如下地址进行下载

http://download.csdn.net/detail/yxtouch/9830337

1 0