redis与spring的集成(七)

7 篇文章 1 订阅

目前做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>



到这里就配置完成,可以跑起来测试了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值