1. 程式人生 > >以SpringMVC框架為中心瘋狂擴充套件-09、新增Redis依賴

以SpringMVC框架為中心瘋狂擴充套件-09、新增Redis依賴

1、配置好Redis伺服器並啟動Redis

2、增加Redis相關的依賴到pom

		<!-- Redis -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.7.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.9.0</version>
		</dependency>
3、配置jedis
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

	<!-- 引入配置檔案 其中order屬性代表其載入順序,而ignoreUnresolvablePlaceholders為是否忽略不可解析的Placeholder,如配置了多個PropertyPlaceholderConfigurer,則需設定為true -->
	<bean id="propertyConfigurerJedis"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="order" value="2" />
		<property name="ignoreUnresolvablePlaceholders" value="true" />
		<property name="location">
			<value>classpath:redis.properties</value>
		</property>
	</bean>

	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxIdle" value="${redis.maxIdle}" />
		<property name="minIdle" value="${redis.minIdle}" />
		<property name="maxTotal" value="${redis.maxTotal}" />
		<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
		<property name="testOnBorrow" value="${redis.testOnBorrow}" />
	</bean>

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

	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory" />
	</bean>
</beans>
#redis的伺服器地址
redis.host=192.168.1.100
#redis的服務埠
redis.port=6379
#最大空閒數
redis.maxIdle=100
#最小空閒數
redis.minIdle=0
#連結資料庫
redis.default.db=0
#最大連線數
redis.maxTotal=600
#最大建立連線等待時間
redis.maxWaitMillis=1000
#指明是否在從池中取出連線前進行檢驗,如果檢驗失敗,則從池中去除連線並嘗試取出另一個
redis.testOnBorrow=true
#許可權
redis.password=123456

4、新增一個rediuis操作的類

import com.syx.customer.model.UserModel;

/** 
 * 使用者Dao介面 Redis
 *
 * @author sunyx 
 * @since JDK 1.8 
 */
public interface UserDao {
	
    /**    
     * 新增使用者到Redis 
     * 
     * @author sunyx 
     * @param user
     * @return 
     * @since JDK 1.8  
     */ 
    boolean add(UserModel user); 
    
    /**    
     * 根據userid獲取UserModel  
     *
     * @author sunyx 
     * @param keyId
     * @return 
     * @since JDK 1.8  
     */ 
    UserModel get(String keyId);
}
import org.springframework.beans.factory.annotation.Autowired;
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.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import com.syx.customer.dao.UserDao;
import com.syx.customer.model.UserModel;

/** 
 * userDao介面實現類,操作redis    
 *
 * @author sunyx 
 * @since JDK 1.8 
 */
@Component("userDao")
public class UserDaoImpl implements UserDao {
	
	@Autowired
    protected RedisTemplate<String,UserModel> redisTemplate;  

	public boolean add(final UserModel user) {
		final boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
            public Boolean doInRedis(RedisConnection connection)  
                    throws DataAccessException {  
            	//獲取 RedisSerializer 
                //keySerializer:這個是對key的預設序列化器。預設值是StringSerializer。
            	//valueSerializer:這個是對value的預設序列化器,預設值是取自DefaultSerializer的JdkSerializationRedisSerializer。
            	//hashKeySerializer:對hash結構資料的hashkey序列化器,預設值是取自DefaultSerializer的JdkSerializationRedisSerializer。
            	//hashValueSerializer:對hash結構資料的hashvalue序列化器,預設值是取自DefaultSerializer的JdkSerializationRedisSerializer。
                final RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
                final byte[] key  = serializer.serialize(user.getId());  
                final byte[] name = serializer.serialize(user.getName());  
                return connection.setNX(key, name);  
            }  
        });  
        return result; 
	}
	
    public UserModel get(final String keyId) {  
    	final UserModel result = redisTemplate.execute(new RedisCallback<UserModel>() {  
            public UserModel doInRedis(RedisConnection connection)  
                    throws DataAccessException {  
                final RedisSerializer<String> serializer = redisTemplate.getStringSerializer();  
                final byte[] key = serializer.serialize(keyId);
                final byte[] value = connection.get(key);  
                if (value == null) {  
                    return null;  
                }  
                final String name = serializer.deserialize(value);  
                return new UserModel(keyId,name);  
            }  
        });  
        return result;  
    }  
	
}
/** 
 * 簡單業務邏輯的實現類
 *
 * @author sunyx 
 * @since JDK 1.8 
 */
@Service("simpleService")
public class SimpleServiceImpl implements SimpleService {
	
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserDao userDao;

	public String put(String userId) {
		final UserModel userModel = userMapper.findUserById(userId);
		userDao.add(userModel);
		return "ok";
	}

	public void get(String userId) {
		final UserModel user = userDao.get(userId);
		System.out.println(user.getId()+","+user.getName());
	}

}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.syx.customer.service.SimpleService;

/** 
 * redis Controller類     
 *
 * @author sunyx 
 * @since JDK 1.8 
 */
@Controller
@RequestMapping("/redis")
public class RedisController{	
	@Autowired
	private SimpleService simpleService;
	
	@RequestMapping("/put")
    public String put(){
		simpleService.put("1");
        return "put";
    }
	
	@RequestMapping("/get")
	public String get(){
		simpleService.get("1");
		return "get";
	}
}
重啟服務

通過/put設定值到redis

通過/get可以過去到redis中的值




異常1:Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool

解決:

1、通過 redis.conf 檢視bind 127.0.0.1 是否被註釋掉了,如果沒有被註釋掉就將其註釋掉,不然就只能被繫結的ip訪問;也可以新增一個新的ip既需要訪問的ip繫結進去。


2、設定auth

2.1通過命令設定

redis-cli
AUTH 123456
如果報錯
CONFIG SET requirepass 123456
AUTH 123456
如果服務重啟,auth就失效了。如果要長期使用,就需要在redis.conf 中設定

2.2在redis.conf 中設定

vi redis.conf
/requirepass
找到
#requirepass foobar
新增
requirepass 123456
退出vi 用redis.config配置啟動redis
redis.server ../redis.config