spring和jedis使用密码操作redis的示例

1、spring配置,下面是一个完整redis配置,密码只需要设置password属性。

<!– jedis pool配置 –>
<bean id=”jedisPoolConfig” class=”redis.clients.jedis.JedisPoolConfig”>
<property name=”maxTotal” value=”${redis.maxActive}” />
<property name=”maxIdle” value=”${redis.maxIdle}” />
<property name=”maxWaitMillis” value=”${redis.maxWait}” />
<!– <property name=”testOnBorrow” value=”${redis.testOnBorrow}” /> –>
</bean>

<bean id=”jedisConnectionFactory”
class=”org.springframework.data.redis.connection.jedis.JedisConnectionFactory”>
<property name=”usePool” value=”true”></property>
<property name=”hostName” value=”${redis.host}” />
<property name=”port” value=”${redis.port}” />
<property name=”password” value=”${redis.pass}” />
<property name=”timeout” value=”${redis.timeout}” />
<!– <property name=”database” value=”${redis.default.db}”></property> –>
<constructor-arg index=”0″ ref=”jedisPoolConfig” />
</bean>

<!– Redis Template –>
<bean id=”redisTemplate” class=”org.springframework.data.redis.core.StringRedisTemplate”>
<property name=”connectionFactory” ref=”jedisConnectionFactory” />
<!– 如果不配置Serializer,那么存储的时候智能使用String,如果用User类型存储,那么会提示错误User can’t cast
to String!!! –>
<property name=”keySerializer”>
<bean
class=”org.springframework.data.redis.serializer.StringRedisSerializer” />
</property>
<property name=”valueSerializer”>
<bean
class=”org.springframework.data.redis.serializer.StringRedisSerializer” />
</property>
<property name=”hashValueSerializer”>
<bean
class=”com.datatang.api.commonmodule.common.serializer.GsonSerializer” />
</property>
</bean>

2、java操作redis,只需要加上jedis.auth(passwd)即可

public static Jedis getRedisConnection(String configFlag){
		String host;
		int port;
		Jedis jedis = null;
		InputStream is = RedisUtil.class.getClassLoader().getResourceAsStream("config/redis.properties");
		Properties pro = new Properties();
		try {
			pro.load(is);
			host = pro.getProperty("redis.host" + configFlag);
			port = Integer.parseInt(pro.getProperty("redis.port" + configFlag));
			jedis = new Jedis(host, port);
			String passwd = pro.getProperty("redis.pass");
			jedis.auth(passwd);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(is != null)
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return jedis;
	}

你可能感兴趣的:(spring)