天天看點

Redis搭建:Maven+Spring+SpringMVC+Redis

下載下傳之後直接解壓得到以下目錄結構

Redis搭建:Maven+Spring+SpringMVC+Redis

點選redis-server.exe即可啟動Redis資料庫

Redis搭建:Maven+Spring+SpringMVC+Redis

輸出資訊:啟動成功、端口号、pid 即啟動成功。

二、搭建開發環境

1>搭建springmvc支援

<!-- 搭建springmvc -->
    <dependency> 
	    <groupId>org.springframework</groupId> 
	    <artifactId>spring-webmvc</artifactId> 
	    <version>4.3.4.RELEASE</version> 
    </dependency> 
	    <dependency> 
	    <groupId>javax.servlet</groupId> 
	    <artifactId>javax.servlet-api</artifactId> 
	    <version>3.1.0</version> 
    </dependency> 
    <dependency> 
	    <groupId>com.fasterxml.jackson.core</groupId> 
	    <artifactId>jackson-core</artifactId> 
	    <version>2.8.4</version> 
    </dependency> 
    <dependency> 
	    <groupId>com.fasterxml.jackson.core</groupId> 
	    <artifactId>jackson-databind</artifactId> 
	    <version>2.8.4</version> 
    </dependency>
           

2>內建Redis

<!-- 內建Redis -->
	<dependency> 
		<groupId>org.springframework.data</groupId> 
		<artifactId>spring-data-redis</artifactId> 
		<version>1.7.5.RELEASE</version> 
	</dependency> 
	<!-- Redis用戶端 --> 
	<dependency> 
		<groupId>redis.clients</groupId> 
		<artifactId>jedis</artifactId> 
		<version>2.9.0</version> 
	</dependency>
           

3>配置Redis:spring-redis.xml

<?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"
	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.3.xsd">

	<!-- 引入redis配置 --> 
	<context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/> 
	<!-- Redis 配置 --> 
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> 
		<property name="maxTotal" value="${redis.pool.maxTotal}" /> 
		<property name="maxIdle" value="${redis.pool.maxIdle}" /> 
		<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" /> 
		<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" /> 
	</bean> 
	<!-- redis單節點資料庫連接配接配置 --> 
	<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> 
		<property name="hostName" value="${redis.ip}" /> 
		<property name="port" value="${redis.port}" /> 
		<!-- <property name="password" value="${redis.pass}" /> --> 
		<property name="poolConfig" ref="jedisPoolConfig" /> 
	</bean> 
	<!-- redisTemplate配置,redisTemplate是對Jedis的對redis操作的擴充,有更多的操作,封裝使操作更便捷 --> 
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> 
		<property name="connectionFactory" ref="jedisConnectionFactory" /> 
	</bean>


</beans>
           

4>配置redis.properties

redis.pool.maxTotal=105 
redis.pool.maxIdle=10 
redis.pool.maxWaitMillis=5000 
redis.pool.testOnBorrow=true 
redis.ip=127.0.0.1 
redis.port=6379
           

三、配置Servlet

此處不在web.xml中配置,采取寫死方式

1.DispatchServlet攔截器

package com.redis.init;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * 配置攔截器
 * @author hc
 *
 */
public class DispatcherServletInit extends AbstractAnnotationConfigDispatcherServletInitializer{

	/**
	 * 配置應用上下文
	 */
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[]{RootConfig.class};
	}

	/**
	 * 配置web上下文
	 */
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class<?>[]{WebConfig.class};
	}

	@Override
	protected String[] getServletMappings() {
		return new String[]{"/"};
	}

}
           

2.應用上下文WebConfig

package com.redis.init;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * 應用上下文
 * @author hc
 *
 */
@Configuration
@ComponentScan(basePackages={"com.redit"},excludeFilters={
		@Filter(type=FilterType.ANNOTATION,value=Controller.class),
		@Filter(type=FilterType.ANNOTATION,value=EnableWebMvc.class)
})
@ImportResource("classpath:spring-*.xml")//引入redis配置檔案
public class RootConfig {

}
           

3.web上下文

package com.redis.init;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan({"com.web"})
public class WebConfig extends WebMvcConfigurerAdapter{

	/**
	 * 配置視圖解析器
	 * @return
	 */
	@Bean
	public ViewResolver viewResolver(){
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".html");
		resolver.setExposePathVariables(true);
		return resolver;
	}
	
	/**
	 * 配置靜态資料總管
	 */
	@Override
	public void configureDefaultServletHandling(
			DefaultServletHandlerConfigurer configurer) {
		super.configureDefaultServletHandling(configurer);
		configurer.enable();
	}
}
           

4.Controller

package com.redis.web;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.redis.core.ListOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("user")
public class UserController {

	@Resource(name="redisTemplate")
	private ListOperations<String, String[]> listUser;
	
	@RequestMapping("/list")
	@ResponseBody
	public List<String[]> list(){
		List<String[]> list=listUser.range("user", 0, -1);
		return list;
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public void add(String... user){
		listUser.leftPush("user", user);
	}
}
           

基本配置完畢,待測試

四、使用Jedis用戶端來測試

1.啟動redis伺服器

<dependency>
		<groupId>redis.clients</groupId>
		<artifactId>jedis</artifactId>
		<version>2.7.2</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-test</artifactId>
		<version>2.5</version>
		<scope>test</scope>
	</dependency>
	<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.4</version>
      <scope>test</scope>
    </dependency>
           

junit盡量用高版本的,不然測試的時候會有版本沖突

2.配置參數

<!-- 配置Jedis連結伺服器參數 -->
	<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> 
		<property name="maxTotal" value="4096"/> 
		<property name="maxIdle" value="200"/> 
		<property name="maxWaitMillis" value="3000"/> 
		<property name="testOnBorrow" value="true" /> 
		<property name="testOnReturn" value="true" /> 
	</bean> 
	<bean id="jedisPool" class="redis.clients.jedis.JedisPool"> 
		<constructor-arg index="0" ref="poolConfig"/> 
		<constructor-arg index="1" value="127.0.0.1"/> 
		<constructor-arg index="2" value="6379" type="int"/> 
	</bean>
           

3.測試

package redis_demo;


import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4Cla***unner;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 使用Jedis來測試redis
 * @author hc
 *
 */
@RunWith(SpringJUnit4Cla***unner.class)
@ContextConfiguration(locations="classpath:spring-redis.xml")
public class RedisTestByJedis extends AbstractJUnit4SpringContextTests{

	@Autowired
	private JedisPool jedisPool;
	
	@Test
	public void basicTest(){
		Jedis jedis = jedisPool.getResource();
		//存值
		jedis.set("user.name", "aaa");
		jedis.set("user.pass", "123");
		
		//取值
		String name = jedis.get("user.name");
		String pass = jedis.get("user.pass");
		//斷言
		Assert.assertEquals("aaa", name);
		//Assert.assertEquals("1234", pass);//錯誤
		Assert.assertEquals("123", pass);
		
		jedis.del("user.name");
		Boolean result = jedis.exists("user.name");
		Assert.assertEquals(false, result);
		
		result = jedis.exists("user.pass");
		Assert.assertEquals(true, result);
		
		jedis.close();
	}
}
           

顯示通過測試

繼續閱讀