Spring+SpringMVC+Redis
Spring+SpringMVC+Redis
- 搭建Redis環境Redis github下載地址 CSDN資源下載地址目前官方推薦的最新穩定版本為3.2.1下載之後直接解壓得到以下目錄結構
點擊redis-server.exe即可啟動Redis資料庫
看到如下截圖,Redis即啟動成功
- 搭建spring環境添加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>
- 集成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>
②配置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-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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>
redis.properties
redis.pool.maxTotal=105redis.pool.maxIdle=10redis.pool.maxWaitMillis=5000redis.pool.testOnBorrow=trueredis.ip=127.0.0.1redis.port=6379
- 配置DispatcherServlet這裡採用硬編碼的方式對DispatcherServlet進行配置,不依賴於web.xml
package white.yu;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;import white.yu.config.RootConfig;import white.yu.config.WebConfig;/** * DispatchServlet 攔截器 * @author white * */public class MainDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { /** * 配置應用上下文 */ @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { RootConfig.class }; } /** * 配置web上下文 */ @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { WebConfig.class }; } /** * 配置DispatcherServlet映射路徑 */ @Override protected String[] getServletMappings() { return new String[] { "/" }; }}
應用上下文RootConfig
package white.yu.config;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.ComponentScan.Filter;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.FilterType;import org.springframework.context.annotation.ImportResource;import org.springframework.stereotype.Controller;import org.springframework.web.servlet.config.annotation.EnableWebMvc;@Configuration@ComponentScan(basePackages = { "white.yu" }, excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Controller.class), @Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) })@ImportResource("classpath:spring/spring-*.xml") //引入redis的配置文件public class RootConfig {}
web上下文 WebConfig
package white.yu.config;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({ "white.yu.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(); }}
- 編寫測試Controller
package white.yu.web;import java.util.List;import javax.annotation.Resource;import org.springframework.beans.factory.annotation.Autowired;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;import white.yu.cache.RedisCache;import white.yu.entity.User;@Controller@RequestMapping("user")public class UserController { @Resource(name = "redisTemplate") private ListOperations<String, User> listOps; @RequestMapping("/list") @ResponseBody public List<User> list() { // 獲取Redis資料庫中的所有user數據 // -1 表示獲取資料庫中的所有數據 List<User> range = listOps.range("user", 0, -1); return range; } @RequestMapping("/add") @ResponseBody public User list(User user){ // 添加到Redis資料庫 listOps.leftPush("user", user); return user; }}
搭建Redis環境
Redis github下載地址CSDN資源下載地址目前官方推薦的最新穩定版本為3.2.1下載之後直接解壓得到以下目錄結構這裡寫圖片描述點擊redis-server.exe即可啟動Redis資料庫這裡寫圖片描述
看到如下截圖,Redis即啟動成功搭建spring環境添加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>
集成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>②配置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-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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>
redis.propertiesredis.pool.maxTotal=105
redis.pool.maxIdle=10redis.pool.maxWaitMillis=5000redis.pool.testOnBorrow=trueredis.ip=127.0.0.1redis.port=6379這裡寫圖片描述- 配置DispatcherServlet這裡採用硬編碼的方式對DispatcherServlet進行配置,不依賴於web.xml
package white.yu;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import white.yu.config.RootConfig;
import white.yu.config.WebConfig;/**
- DispatchServlet 攔截器
- @author white
- */public class MainDispatcherServletInitializer extendsAbstractAnnotationConfigDispatcherServletInitializer {
/**
- 配置應用上下文*/@Overrideprotected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
/**
- 配置web上下文*/@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class<?>[] { WebConfig.class };}
/**
- 配置DispatcherServlet映射路徑*/
@Override
protected String[] getServletMappings() {return new String[] { "/" };}
}
應用上下文RootConfigpackage white.yu.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.FilterType;import org.springframework.context.annotation.ImportResource;import org.springframework.stereotype.Controller;import org.springframework.web.servlet.config.annotation.EnableWebMvc;@Configuration
@ComponentScan(basePackages = { "white.yu" }, excludeFilters = {@Filter(type = FilterType.ANNOTATION, value = Controller.class),@Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) })@ImportResource("classpath:spring/spring-*.xml") //引入redis的配置文件public class RootConfig {}
web上下文 WebConfigpackage white.yu.config;
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({ "white.yu.web" })public class WebConfig extends WebMvcConfigurerAdapter {/** * 配置視圖解析器 * * @return */@Beanpublic ViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".html"); resolver.setExposePathVariables(true); return resolver;}/** * 配置靜態資源處理器 */@Overridepublic void configureDefaultServletHandling( DefaultServletHandlerConfigurer configurer) { super.configureDefaultServletHandling(configurer); configurer.enable();}
}
編寫測試Controllerpackage white.yu.web;import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
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;import white.yu.cache.RedisCache;
import white.yu.entity.User;@Controller
@RequestMapping("user")public class UserController {@Resource(name = "redisTemplate")private ListOperations<String, User> listOps;@RequestMapping("/list")@ResponseBodypublic List<User> list() { // 獲取Redis資料庫中的所有user數據 // -1 表示獲取資料庫中的所有數據 List<User> range = listOps.range("user", 0, -1); return range;}@RequestMapping("/add")@ResponseBodypublic User list(User user){ // 添加到Redis資料庫 listOps.leftPush("user", user); return user;}
}
作者: Hi小魚_White
鏈接:https://www.imooc.com/article/15163
來源:慕課網
本文原創發佈於慕課網 ,轉載請註明出處,謝謝合作!
推薦閱讀:
※Linux安裝redis,並設置訪問許可權,及使用可視化工具
※知乎是如何做緩存的?
※集群環境中資料庫與緩存的三板斧
※scrapy-redis 和 scrapy 有什麼區別?
TAG:Redis |