<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
<!-- Redis Connection Factory --> <bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="192.168.2.1" p:port="6379" p:use-pool="true" /> <!-- redis template definition --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="jedisConnFactory" />
例 11.2. Spring Data Redis Example
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/css/" mapping="/css/**" />
<context:component-scan base-package="cn.netkiller.controller" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<!-- <property name="viewNames" value="*.jsp" /> -->
</bean>
<bean id="configuracion"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:resources/development.properties" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.netkiller.mapper" />
</bean>
<bean id="userService" class="cn.netkiller.service.UserService">
</bean>
<!-- Redis Connection Factory -->
<bean id="jedisConnFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="192.168.2.1" p:port="6379" p:use-pool="true" />
<!-- redis template definition -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnFactory" />
</beans>
package cn.netkiller.controller;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import cn.netkiller.model.User;
@Controller
public class CacheController {
// inject the actual template
@Autowired
private RedisTemplate<String, String> template;
// inject the template as ListOperations
@Resource(name = "redisTemplate")
private ListOperations<String, String> listOps;
@RequestMapping("/cache")
public ModelAndView cache() {
String message = "";
User user = new User();
user.setId("1");
user.setName("Neo");
user.setAge(30);
String key = "user";
listOps.leftPush(key, user.toString());
message = listOps.leftPop(key);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
template.opsForValue().set("key", user.toString());
return new ModelAndView("index/index", "variable", message);
}
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<br>
<div style="text-align:center">
<h2>
${variable}
</h2>
</div>
</body>
</html>
请求URL http://your.domain.com/your.html
[root@master ~]# redis-cli redis 127.0.0.1:6379> keys * 1) "\xac\xed\x00\x05t\x00\x04user" 2) "key" redis 127.0.0.1:6379> get key "\xac\xed\x00\x05t\x00\x1dUser [id=1, name=Neo, age=30]"
![]() | 提示 |
|---|---|
|
Spring Redis 默认使用 Byte数据类型存储Key,在redis-cli中会看到 "\xac\xed\x00\x05t\x00\x04" 前缀不方便get操作,所以我们会设置使用字符串,通过 template.setKeySerializer(new StringRedisSerializer()); 实现 |
注意Spring4 与 1.9.1.RELEASE有兼容性问题,日志提示 Error creating bean with name 'mongoTemplate' defined in ServletContext resource
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.8.1.RELEASE</version> </dependency>
<mongo:db-factory id="mongoDbFactory" host="${mongo.host}" port="${mongo.port}" dbname="${mongo.database}" />
<!-- username="${mongo.username}" password="${mongo.password}" -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
<mongo:mapping-converter id="converter" db-factory-ref="mongoDbFactory"/>
<bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
<constructor-arg ref="mongoDbFactory"/>
<constructor-arg ref="converter"/>
</bean>
例 11.3. Spring Data MongoDB - springframework-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd
">
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<mvc:resources location="/zt/" mapping="/zt/**" />
<mvc:resources location="/sm/" mapping="/sm/**" />
<mvc:resources location="/module/" mapping="/module/**" />
<context:component-scan base-package="cn.netkiller.controller" />
<!-- <context:property-placeholder location="classpath:resources/development.properties" /> -->
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="configuracion" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:resources/development.properties" />
</bean>
<!-- MongoDB Connection Factory -->
<mongo:db-factory id="mongoDbFactory" host="${mongo.host}" port="${mongo.port}" dbname="${mongo.database}" />
<!-- username="${mongo.username}" password="${mongo.password}" -->
<!-- MongoDB template definition -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
<!-- MongoDB GridFS template definition -->
<mongo:mapping-converter id="converter" db-factory-ref="mongoDbFactory"/>
<bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
<constructor-arg ref="mongoDbFactory"/>
<constructor-arg ref="converter"/>
</bean>
<!-- Redis Connection Factory -->
<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="192.168.2.1" p:port="6379" p:use-pool="true" />
<!-- redis template definition -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="jedisConnFactory" />
</beans>
development.properties 配置内容
mongo.host=192.168.4.1 mongo.port=27017 mongo.username=test mongo.password=passw0rd mongo.database=website
package cn.netkiller.pojo;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "tracker")
public class Tracker {
@Id
private String id;
private String name;
private String unique;
private String hostname;
private String referrer;
private String href;
public Tracker() {
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUnique() {
return unique;
}
public void setUnique(String unique) {
this.unique = unique;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getReferrer() {
return referrer;
}
public void setReferrer(String referrer) {
this.referrer = referrer;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
@Override
public String toString() {
return "Tracker [id=" + id + ", name=" + name + ", unique=" + unique + ", hostname=" + hostname + ", referrer=" + referrer + ", href=" + href + "]";
}
}
package cn.netkiller.controller;
import cn.netkiller.pojo.Tracker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
@Controller
public class TrackerController {
@Autowired
private MongoTemplate mongoTemplate;
public TrackerController() {
}
@RequestMapping("/tracker/test")
@ResponseBody
String hello() {
return "Hello World!";
}
@RequestMapping("/tracker")
@ResponseBody
String execute() {
Tracker tracker = new Tracker();
tracker.setName("test");
tracker.setUnique("111223456");
tracker.setHostname("www.example.com");
tracker.setHref("http://example.com/test.html");
tracker.setReferrer("http://example.com/");
this.mongoTemplate.insert(tracker);
return tracker.toString();
}
}
> db.tracker.find();
{ "_id" : ObjectId("5757c0b92c526a6bda5eea3a"), "_class" : "cn.netkiller.repositories.Tracker", "name" : "test", "unique" : "111223456", "hostname" : "www.example.com", "referrer" : "http://example.com/", "href" : "http://example.com/test.html" }