Spring 整合 redis (二)

12 篇文章 0 订阅
7 篇文章 0 订阅

                             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.133
redis.port=6379
redis.pass=123

# \u6700\u5927\u7A7A\u95F2\u6570
redis.maxIdle=10
# \u6700\u5927\u8FDE\u63A5\u6570
redis.minIdle=1
# \u6700\u5927\u7B49\u5F85\u6570
redis.maxWait=10
redis.testOnBorrow=true

3 新建spring配置文件 applicationContext.xml

	<!-- 读取redis.properties文件 -->
	<bean
		class="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 {
	@Resource
	private RedisTemplate<String, String> redisTemplate;

	@Test
	public 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;
			}
		});
	}

	@Test
	public 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 implementation
SLF4J: 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值