1.单数据源
(1)pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.whl.demo</groupId>
<artifactId>springboot-redis</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.13.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestone</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
(2)application.properties
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.0.49
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=123456
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
Application.java
package com.whl.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
(3)User.java
package com.whl.demo.domain;
public class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
(4)UserService.java
package com.whl.demo.dao;
public interface UserService {
public void saveUser();
}
(5)UserMapper.java
package com.whl.demo.mapper;
import com.whl.demo.dao.UserService;
import com.whl.demo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import java.util.concurrent.TimeUnit;
@Service("userService")
public class UserMapper implements UserService{
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public void saveUser() {
User user = new User();
user.setId("003");
user.setName("zhangwuli");
stringRedisTemplate.opsForHash().put("test-user-info-list",user.getId(),JSON.toJSONString(user));
stringRedisTemplate.expire("test-user-info-list",1000, TimeUnit.SECONDS);
}
// 相关用法
//
// stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);//向redis里存入数据和设置缓存时间
// stringRedisTemplate.boundValueOps("test").increment(-1);//val做-1操作
// stringRedisTemplate.opsForValue().get("test")//根据key获取缓存中的val
// stringRedisTemplate.boundValueOps("test").increment(1);//val +1
// stringRedisTemplate.getExpire("test")//根据key获取过期时间
// stringRedisTemplate.getExpire("test",TimeUnit.SECONDS)//根据key获取过期时间并换算成指定单位
// stringRedisTemplate.delete("test");//根据key删除缓存
// stringRedisTemplate.hasKey("546545");//检查key是否存在,返回boolean值
// stringRedisTemplate.opsForSet().add("red_123", "1","2","3");//向指定key中存放set集合
// stringRedisTemplate.expire("red_123",1000 , TimeUnit.MILLISECONDS);//设置过期时间
// stringRedisTemplate.opsForSet().isMember("red_123", "1")//根据key查看集合中是否存在指定数据
// stringRedisTemplate.opsForSet().members("red_123");//根据key获取set集合
}
(6)UserController.java
package com.whl.demo.controller;
import com.whl.demo.dao.UserService;
import com.whl.demo.service.DuplicateSubmitToken;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
@RestController
@RequestMapping("user")
public class UserController {
@Resource
UserService userService;
// 防止表单重复提交
@DuplicateSubmitToken
@ResponseBody
@RequestMapping(value = "addUser.do")
public Map<String, Object> addUser(HttpServletRequest request, @RequestParam String aa){
userService.saveUser();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// return "1";
Map<String, Object> map = new HashMap();
request.getSession().setAttribute("request Url", request.getRequestURL());
map.put("request Url", request.getRequestURL());
return map;
}
@RequestMapping(value = "/test", method = RequestMethod.GET)
public Map<String, Object> firstResp (HttpServletRequest request){
Map<String, Object> map = new HashMap();
request.getSession().setAttribute("request Url", request.getRequestURL());
map.put("request Url", request.getRequestURL());
return map;
}
@DuplicateSubmitToken
@RequestMapping(value = "/test/d", method = RequestMethod.GET)
public Map<String, Object> test (HttpServletRequest request) throws Exception {
Random r=new Random();
int i = r.nextInt(3);
if (i==2){
throw new Exception("有异常");
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Map<String, Object> map = new HashMap();
request.getSession().setAttribute("request Url", request.getRequestURL());
map.put("request Url", request.getRequestURL());
return map;
}
}
2.多数据源
(1) pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.whl.demo</groupId>
<artifactId>springboot-redis-more</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.13.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestone</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
(2) application.properties,redis.properties 一样的
#===============Redis配置=========================
#redis连接池配置
#最大连接数
spring.redis.pool.max-active=8
#最大空闲连接数
spring.redis.pool.max-idle=8
#连接池阻塞等待时间
spring.redis.pool.max-wait=-1
spring.redis.pool.min-idle=0
#redis cluster集群配置
spring.redis.sentinel.master= # Name of Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.
#redis多实例配置,但至少要配一组作为默认配置
#默认redis
spring.redis.database=0
spring.redis.host=192.168.0.46
spring.redis.port=6379
spring.redis.timeout=0
#redis2
spring.redis2.database=0
spring.redis2.host=183.243.46.21
spring.redis2.port=11121
spring.redis2.timeout=0
#redis3
#....
(3)DefaultRedisConfig.java
package com.whl.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
//PropertySource注解设置使用的resource目录下配置文件名称,
//不设置默认为resource/application.properties
//@PropertySource(value = "classpath:/redis.properties")
@Configuration
@EnableCaching
public class DefaultRedisConfig extends RedisConfig {
@Value("${spring.redis.database}")
private int dbIndex;
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Primary
@Bean
public JedisConnectionFactory defaultRedisConnectionFactory() {
return newJedisConnectionFactory(dbIndex,host, port, timeout);
}
@Bean(name = "DefaultRedisTemplate")
public RedisTemplate defaultRedisTemplate() {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(defaultRedisConnectionFactory());
setSerializer(template);
template.afterPropertiesSet();
return template;
}
@Bean(name = "DefaultStringRedisTemplate")
public StringRedisTemplate defaultStringRedisTemplate() {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(defaultRedisConnectionFactory());
template.afterPropertiesSet();
return template;
}
}
(4)RedisConfig.java
package com.whl.demo.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
import java.lang.reflect.Method;
/**
* Redis多实例配置
*/
@Configuration
@EnableCaching
public class RedisConfig {
@Value("${spring.redis.pool.max-active}")
private int redisPoolMaxActive;
@Value("${spring.redis.pool.max-idle}")
private int redisPoolMaxIdle;
@Value("${spring.redis.pool.min-idle}")
private int redisPoolMinIdle;
@Value("${spring.redis.pool.max-wait}")
private int redisPoolMaxWait;
@Bean
public KeyGenerator keyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* 创建连接
* @param host
* @param port
* @param timeout
* @return
*/
public JedisConnectionFactory newJedisConnectionFactory(int index,String host,int port,int timeout){
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setDatabase(index);
factory.setHostName(host);
factory.setPort(port);
factory.setTimeout(timeout); //设置连接超时时间
//testOnBorrow为true时,返回的连接是经过测试可用的
factory.setPoolConfig(poolCofig(redisPoolMaxIdle,redisPoolMinIdle,redisPoolMaxActive,redisPoolMaxWait,true));
System.out.println("redis config========="+host);
return factory;
}
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
// Number of seconds before expiration. Defaults to unlimited (0)
//cacheManager.setDefaultExpiration(10); //设置key-value超时时间
return cacheManager;
}
public JedisPoolConfig poolCofig(int maxIdle, int minIdle,int maxTotal,long maxWaitMillis,boolean testOnBorrow) {
JedisPoolConfig poolCofig = new JedisPoolConfig();
poolCofig.setMaxIdle(maxIdle);
poolCofig.setMinIdle(minIdle);
poolCofig.setMaxTotal(maxTotal);
poolCofig.setMaxWaitMillis(maxWaitMillis);
poolCofig.setTestOnBorrow(testOnBorrow);
return poolCofig;
}
public void setSerializer(RedisTemplate template) {
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setKeySerializer(new StringRedisSerializer());
}
}
(5)TestService.java
package com.whl.demo.service;
public interface TestService {
public void add();
}
(6)TestServiceImpl.java
package com.whl.demo.service.impl;
import com.whl.demo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Component
public class TestServiceImpl implements TestService{
@Autowired
@Resource(name = "DefaultStringRedisTemplate")
private StringRedisTemplate defaultStringRedis;
@Override
public void add() {
defaultStringRedis.opsForHash().put("user-info-list","aaaaa","bbbbbbbb");
}
}
(7)TestController.java
package com.whl.demo.controller;
import com.whl.demo.service.TestService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("test")
public class TestController {
@Resource
TestService testService;
@ResponseBody
@RequestMapping(value = "add")
public void add(){
testService.add();
}
}
代码详见 https://github.com/aa57847225/redis.git code下