用Memcached,对于缓存对象大小有要求,单个对象不得大于1MB,且不支持复杂的数据类型,譬如SET等。基于这些限制,有必要考虑Redis!
言归正传,目前Redis大概有3中基于Java语言的Client:
- Jredis
- Jedis
- Redis4J 这里只说Jedis,因为它是官方提供的唯一Redis Client For Java Provider!
一、简单使用Jedis
需要Jedis就从Maven获取吧! Maven Pom.xml
代码语言:javascript复制 <dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
jedis 的简单实用:
代码语言:javascript复制package redis;
import redis.clients.jedis.Jedis;
import java.util.List;
public class HelloRedis {
public static void main(String[] args){
Jedis jedis = new Jedis("10.20.112.33",6379);
System.out.println("Connection to server sucessfully");
//check whether server is running or not
System.out.println("Server is running: " jedis.ping());
jedis.lpush("wonder-list", "Redis");
jedis.lpush("wonder-list", "Mongodb");
jedis.lpush("wonder-list", "Mysql");
// Get the stored data and print it
List<String> list = jedis.lrange("wonder-list", 0 ,5);
for(int i=0; i<list.size(); i ) {
System.out.println("Stored string in redis:: " list.get(i));
}
}
}
二、池化使用Jedis
Jedis使用commons-pool完成池化实现。
先做个配置文件:
代码语言:javascript复制#最大分配的对象数
redis.pool.maxTotal=1024
#最大能够保持idle状态的对象数
redis.pool.maxIdle=200
#当池内没有返回对象时,最大等待时间,单位为妙
redis.pool.maxWait=1000
#当调用borrow Object方法时,是否进行有效性检查
redis.pool.testOnBorrow=true
#当调用return Object方法时,是否进行有效性检查
redis.pool.testOnReturn=true
#连接超时时是否阻塞,false时报异常,ture阻塞直到超时, 默认true
redis.pool.blockWhenExhausted=true
#超时时间 默认2000
redis.timeout=2000
#IP
redis.host=10.20.112.33
#Port
redis.port=6379
在静态代码中完成初始化
代码语言:javascript复制package redis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.ResourceBundle;
public class JedisConfig{
public static JedisPool pool;
static {
ResourceBundle bundle = ResourceBundle.getBundle("redisProperty.redis");
if (bundle == null) {
throw new IllegalArgumentException("[redis.properties] is not found!");
}
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(Integer.valueOf(bundle.getString("redis.pool.maxTotal")));
config.setMaxIdle(Integer.valueOf(bundle.getString("redis.pool.maxIdle")));
config.setMaxWaitMillis(Long.valueOf(bundle.getString("redis.pool.maxWait")));
config.setTestOnBorrow(Boolean.valueOf(bundle.getString("redis.pool.testOnBorrow")));
config.setTestOnReturn(Boolean.valueOf(bundle.getString("redis.pool.testOnReturn")));
pool = new JedisPool(config, bundle.getString("redis.host"),Integer.valueOf(bundle.getString("redis.port")));
}
}
然后,修改前面那段jedis代码 主要是更改获取方式 改为从对象池中,获取Jedis实例 切记,最后使用后,释放Jedis对象
代码语言:javascript复制package redis;
import redis.clients.jedis.Jedis;
import redis.clients.util.Pool;
import java.util.List;
public class HelloRedis {
public static void main(String[] args){
// Jedis jedis = new Jedis("10.20.112.33",6379);
// 从池中获取一个Jedis对象
Jedis jedis = JedisConfig.pool.getResource();
System.out.println("Connection to server sucessfully");
//check whether server is running or not
System.out.println("Server is running: " jedis.ping());
jedis.lpush("wonder-list", "Redis");
jedis.lpush("wonder-list", "Mongodb");
jedis.lpush("wonder-list", "Mysql");
// Get the stored data and print it
List<String> list = jedis.lrange("wonder-list", 0 ,5);
for(int i=0; i<list.size(); i ) {
System.out.println("Stored string in redis:: " list.get(i));
}
// 释放对象池
JedisConfig.pool.close();
}
}
同样执行成功:
代码语言:javascript复制Connection to server sucessfully
Server is running: PONG
Stored string in redis:: Mysql
Stored string in redis:: Mongodb
Stored string in redis:: Redis
Stored string in redis:: Mysql
Stored string in redis:: Mongodb
Stored string in redis:: Redis
三、一致性哈希
Memcached完全基于分布式集群,而Redis是Master-Slave,如果想把Reids,做成集群模式,无外乎多做几套Master-Slave,每套Master-Slave完成各自的容灾处理,通过Client工具,完成一致性哈希。
PS:Memcached是在Server端完成Sharding,Redis只能依靠各个Client做Sharding。可能会在Redis 3.0系列支持Server端Sharding。
代码语言:javascript复制JedisShardInfo jedisShardInfo1 = new JedisShardInfo(
bundle.getString("redis1.ip"), Integer.valueOf(bundle .getString("redis.port")));
JedisShardInfo jedisShardInfo2 = new JedisShardInfo(
bundle.getString("redis2.ip"), Integer.valueOf(bundle .getString("redis.port")));
List<JedisShardInfo> list = new LinkedList<JedisShardInfo>();
list.add(jedisShardInfo1);
list.add(jedisShardInfo2);
初始化ShardedJedisPool代替JedisPool:
代码语言:javascript复制ShardedJedisPool pool = new ShardedJedisPool(config, list);
改由ShardedJedis,获取Jedis对象:
代码语言:javascript复制// 从池中获取一个Jedis对象
ShardedJedis jedis = JedisConfig.pool.getResource();
String keys = "name";
String value = "snowolf";
// 删数据
jedis.del(keys);
// 存数据
jedis.set(keys, value);
// 取数据
String v = jedis.get(keys);
System.out.println(v);
// 释放对象池
pool.close();
四、Spring封装参考
Ok,完成上述代码足够完成简单任务,如果有必要,
可以用spring-data-redis
封装初始化:
首先加入maven依赖
代码语言:javascript复制<?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.wq</groupId>
<artifactId>beauty</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- redis 版本 -->
<redis.version>2.9.0</redis.version>
<spring.redis.version>1.8.4.RELEASE</spring.redis.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- mail and spring-context-support for send email -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.2</version>
</dependency>
<!-- /email -->
<!-- mysql驱动 start-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mysql驱动 end-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${redis.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
创建一个spring-redis.xml:
代码语言:javascript复制<?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-4.3.xsd"
default-lazy-init="false">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:redisProperty/redis.properties" />
<!-- redis数据源 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最大空闲数 -->
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<!-- 最大空连接数 -->
<property name="maxTotal" value="${redis.pool.maxTotal}" />
<!-- 最大等待时间 -->
<property name="maxWaitMillis" value="${redis.pool.maxWait}" />
<!-- 连接超时时是否阻塞,false时报异常,ture阻塞直到超时, 默认true -->
<property name="blockWhenExhausted" value="${redis.pool.blockWhenExhausted}" />
<!-- 返回连接时,检测连接是否成功 -->
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
<property name="testOnReturn" value="${redis.pool.testOnReturn}" />
</bean>
<!-- Spring-redis连接池管理工厂 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<!-- IP地址 -->
<property name="hostName" value="${redis.host}" />
<!-- 端口号 -->
<property name="port" value="${redis.port}" />
<!-- 超时时间 默认2000-->
<property name="timeout" value="${redis.timeout}" />
<!-- 连接池配置引用 -->
<property name="poolConfig" ref="poolConfig" />
<!-- usePool:是否使用连接池 -->
<property name="usePool" value="true"/>
</bean>
<!-- redis template definition -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<!--开启事务 -->
<property name="enableTransactionSupport" value="true"></property>
</bean>
<!--自定义redis工具类,在需要缓存的地方注入此类 -->
<bean id="redisrCacheManager" class="redis.RedisTemplet">
<property name="redisTemplate" ref="redisTemplate" />
</bean>
</beans>
创建对应的reidis工具类
代码语言:javascript复制package redis;
import org.springframework.data.redis.core.RedisTemplate;
public class RedisTemplet {
protected RedisTemplate<String, Object> redisTemplate;
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public RedisTemplate getRedisTemplate(){
return redisTemplate;
}
}
/**
* 获取list缓存的内容
*
* @param key
* 键
* @param start
* 开始
* @param end
* 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
创建test类
代码语言:javascript复制import org.junit.Test;
import org.springframework.stereotype.Component;
import redis.JedisConfig;
import redis.RedisTemplet;
import redis.clients.jedis.Jedis;
import javax.annotation.Resource;
import java.util.List;
@Component
public class RedisTest extends BaseTest{
@Resource(name="redisrCacheManager")
private RedisTemplet redisTemplet;
@Test
public void testByCode(){
// Jedis jedis = new Jedis("10.20.112.33",6379);
// 从池中获取一个Jedis对象
Jedis jedis = JedisConfig.pool.getResource();
System.out.println("Connection to server sucessfully");
//check whether server is running or not
System.out.println("Server is running: " jedis.ping());
jedis.lpush("wonder-list", "Redis");
jedis.lpush("wonder-list", "Mongodb");
jedis.lpush("wonder-list", "Mysql");
// Get the stored data and print it
List<String> list = jedis.lrange("wonder-list", 0 ,5);
for(int i=0; i<list.size(); i ) {
System.out.println("Stored string in redis:: " list.get(i));
}
// 释放对象池
JedisConfig.pool.close();
}
@Test
public void testByXml(){
System.out.println("下面是通过xml配置获取redis pool中对象,然后获取数据:");
List list = redisTemplet.lGet("wonder-list",0,5);
System.out.println(list);
}
}
通过程序与之前的一致 通过xml的测试输出如下:
代码语言:javascript复制21:03:39.312 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.boot.test.mock.mockito.MockitoBeans'
下面是通过xml配置获取redis pool中对象,然后获取数据:
21:03:39.363 [main] DEBUG org.springframework.data.redis.core.RedisConnectionUtils - Opening RedisConnection
[Mysql, Mongodb, Redis, Mysql, Mongodb, Redis]
项目目录结构如下:
如图