redis與spring的集成(七)

目前做javaEE項目,使用spring來管理javaBean已經基本成了標準,這篇文章就是講解使用spring來管理redis的bean。

由於使用的是redis集羣(3.0以後),故要使用jedis-2.5.2.jar以上版本。

在此例子中,涉及到四個文件,其中新加三個RedisInterface.java、RedisCluster.java、redis-database.xml、RedisRest.java,修改我們的spring主配置文件applicationContext-core.xml、web.xml

開發步驟

1. 開發RedisInterface.java,此接口是定義redis的操作的所有方法,此例子只定義的三個。自己有需要可以把redis中所有方法實現,參考jedis

<span style="font-size:14px;">package com.gyc.redis;


public interface RedisInterface{

	boolean set(String key,int expiresTime, Object value);
	Object get(String key);
	boolean delete(String key);

	//在此接口中把redis要實現的接口全部定義,如查詢key是否存在、key的剩餘時間,其它四種類型(hashmap、list、set、sortset)類型的所有方法等等
}
</span>


2. 開發RedisCluster.java

<span style="font-size:14px;">package com.gyc.redis;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.InitializingBean;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.Protocol;

public class RedisCluster implements RedisInterface,InitializingBean {

	protected JedisCluster jedisCluster;

	protected String servers = "";
	
	protected int timeout = Protocol.DEFAULT_TIMEOUT;

	protected int redirections = 4;

	public RedisCluster() {
	}

	//添加字符串
	public boolean set(String key, int expiresTime, Object value) {
		try{
			this.jedisCluster.set(key, (String)value);
			if (expiresTime > 0){
				this.jedisCluster.expire(key, expiresTime);
			}
			return true;
		} catch (Exception e){
			throw new RuntimeException(e.getMessage(), e);
		} finally{
		}
	}
	
	//根據key得到值爲字符串類型的值
	public Object get(String key) {
		try{
			String data = this.jedisCluster.get(key);
			if (data == null){
				return null;
			} else{
				return data;
			}
		} catch (Exception e){
			throw new RuntimeException(e.getMessage(), e);
		} finally{

		}
	}

	//刪除key
	public boolean delete(String key) {
		try{
			this.jedisCluster.del(key);
			return true;
		} catch (Exception e){
			throw new RuntimeException(e.getMessage(), e);
		} finally{
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// 根據分號將cluster地址轉成List
		List<String> als = Arrays.asList(this.servers.split(";"));
		if (als.isEmpty()){
			throw new Exception("Redis Server Configuration is empty!");
		}
		// 定義一個Set
		Set<HostAndPort> shap = new HashSet<HostAndPort>();
		// 將List中的地址分成host和port,加入到Set中
		for (String s : als){
			int splitNum = s.indexOf(":");
			String host = s.substring(0, splitNum);
			int port = Integer.parseInt(s.substring(splitNum + 1));
			shap.add(new HostAndPort(host, port));
		}
		jedisCluster = new JedisCluster(shap, this.timeout, this.redirections);
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public void setRedirections(int redirections) {
		this.redirections = redirections;
	}

	public void setServers(String servers) {
		this.servers = servers;
	}
}
</span>


3. 開發redis-database.xml

<span style="font-size:14px;"><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:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		 http://www.springframework.org/schema/context   
     http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
	<description>redis的配置文件</description>
	
	<!--redis cluster -->
	<bean id="redisAccessor" class="com.gyc.redis.RedisClientCluster">
		<property name="servers">
			<value>127.0.0.1:6637;127.0.0.1:6638;127.0.0.1:6639</value>
		</property>
		<property name="redirections">
			<value>3</value>
		</property>
		<property name="timeout">
			<value>2000</value>
		</property>
	</bean>

</beans></span>

4. 修改我們的spring主配置文件applicationContext-core.xml。在spring的主配置文件中添加redis配置,redis-database.xml

<span style="font-size:14px;"><?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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<import resource="redis-database.xml"></import> 		
</beans></span>

5. 在web.xml文件中配置contextConfigLocation


<span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?></span></span>

<span style="font-size:14px;">
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<!-- Spring配置 -->
	<listener> 
	  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
	</listener> 
	   
	  
	<!-- 指定Spring Bean的配置文件所在目錄。默認配置在WEB-INF目錄下 -->
	<context-param> 
	  <param-name>contextConfigLocation</param-name> 
	  <param-value>classpath:applicationContext-core.xml</param-value> 
	</context-param></span>
<span style="font-size:14px;"></web-app>
</span>


6. 開發RedisRest.java,此類是Controller

<span style="font-size:14px;">package com.gyc.dmz.rest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

import com.gyc.redis.RedisInterface;


@Controller
@RequestMapping("redis")
public class RedisRest {
	@Autowired
	RedisInterface redisAccessor;
	
	@RequestMapping("addRedisValueByKey")
	//測試url:http://localhost:7001/springgyc/redis/addRedisValueByKey.do?key=name&value=zhangsan
	public String addRedisValueByKey(HttpServletRequest request,
			HttpServletResponse response){
		System.out.println("geyc--------addRedisValueByKey-----");
		String key = request.getParameter("key");
		String value = request.getParameter("value");
		boolean status = redisAccessor.set(key, -1, value);
		if (status) {
			request.setAttribute("value", status);
		}
		return "redis";
	}
	
	@RequestMapping("delRedisValueByKey")
	//測試url:http://localhost:7001/springgyc/redis/delRedisValueByKey.do?key=name
	public String delRedisValueByKey(HttpServletRequest request,
			HttpServletResponse response){
		System.out.println("geyc--------delRedisValueByKey-----");
		String key = request.getParameter("key");
		boolean status = redisAccessor.delete(key);
		if (status) {
			request.setAttribute("value", status);
		}
		return "redis";
	}
	
	@RequestMapping("queryRedisValueByKey")
	//測試url:http://localhost:7001/springgyc/redis/queryRedisValueByKey.do?key=name
	public String queryRedisValueByKey(HttpServletRequest request,
			HttpServletResponse response){
		System.out.println("geyc--------queryRedisValueByKey-----");
		String key = request.getParameter("key");
		Object obj = redisAccessor.get(key);
		if (obj != null) {
			request.setAttribute("value", (String)obj);
		}
		return "redis";
	}
}
</span>



到這裏就配置完成,可以跑起來測試了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章