Spring 整合 redis (二)

来源:互联网 发布:sql server 2012密钥 编辑:程序博客网 时间:2024/06/05 17:26

                             Spring 整合 redis (二)

1 新建一个maven项目 构建pom文件

<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>4.1.3.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>4.1.3.RELEASE</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>4.1.3.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>4.1.3.RELEASE</version></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>1.7.1.RELEASE</version></dependency>

2  新建一个properties文件 redis.properties

redis.host=192.168.126.133redis.port=6379redis.pass=123# \u6700\u5927\u7A7A\u95F2\u6570redis.maxIdle=10# \u6700\u5927\u8FDE\u63A5\u6570redis.minIdle=1# \u6700\u5927\u7B49\u5F85\u6570redis.maxWait=10redis.testOnBorrow=true

3 新建spring配置文件 applicationContext.xml

<!-- 读取redis.properties文件 --><beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><list><value>classpath:redis.properties</value></list></property></bean><!-- 连接池配置 --><bean id="jpoolConfig" class="redis.clients.jedis.JedisPoolConfig"p:maxIdle="${redis.maxIdle}" p:maxWaitMillis="${redis.maxWait}"p:testOnBorrow="${redis.testOnBorrow}" /><!--链接配置 --><bean id="jconnectionFactory"class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"p:hostName="${redis.host}" p:port="${redis.port}" p:poolConfig-ref="jpoolConfig" /><!-- Redis模版类,用于操作redis --><bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"p:connectionFactory-ref="jconnectionFactory"></bean>

4 新建一个测试类 RedisTest.class

package com.chainhu.redis.test;import java.util.concurrent.TimeUnit;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.dao.DataAccessException;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.core.RedisCallback;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.chainhu.jedis.domain.User;@RunWith(value = SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:applicationContext.xml" })public class RedisTest {@Resourceprivate RedisTemplate<String, String> redisTemplate;@Testpublic void test1() {User user = new User();user.setUsername("xiaozhang");user.setGender("nan");user.setPassword("123");saveUser(user);}    /****     * 保存信息到redis     * @param user     */public void saveUser(final User user) {redisTemplate.execute(new RedisCallback<Object>() {public Object doInRedis(RedisConnection connection) throws DataAccessException {connection.set(redisTemplate.getStringSerializer().serialize(user.getUsername() + ""),redisTemplate.getStringSerializer().serialize(user.toString() + ""));// 设置redis缓存时间redisTemplate.expire(user.getUsername(), 30, TimeUnit.SECONDS);return null;}});}    /****     * 从redis中获取值     * @param username     * @return     */public User getUser(final String username) {return redisTemplate.execute(new RedisCallback<User>() {public User doInRedis(RedisConnection connection) throws DataAccessException {byte[] key = redisTemplate.getStringSerializer().serialize(username + "");if (connection.exists(key)) {byte[] value = connection.get(key);String user = redisTemplate.getStringSerializer().deserialize(value);System.out.println(user);User ruser = new User();ruser.setUsername(username);return ruser;}return null;}});}@Testpublic void Test2() {String username = "xiaozhang";User user = getUser(username);System.out.println(user);}}

5  解决运行时异常问题

5.1 运行test1 方法 当控制台报错,出现如下图所示错误时

DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified,no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. 


此时我们需要去修改一下redis的配置文件redis.conf, 找到你服务器上redis的配置文件并打开

将图中红色框部分放开(去掉前面的#号)然后保存,在去重启redis,再次运行test1方法,如果出现如下异常

NOAUTH Authentication required.
此时,我们有两种方式去修改

第一种 修改redis.conf文件 将图中部分注释掉,将redis修改成不需要密码也能登陆的形式

第二种 修改applicationContext.xml 文件修改下图所示部分

修改完成后,在次运行test1方法,没有异常的情况下,在运行test2方法,控制台输出如下

SLF4J: Defaulting to no-operation (NOP) logger implementationSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.User [username=xiaozhang, password=123, gender=nan]User [username=xiaozhang, password=null, gender=null]

此时就说明已经成功了!


0 0
原创粉丝点击