Redis
*Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Hash), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。*
redis创建
在spring项目中,可把redis作为通用工具创建在utils文件夹下
package cn.xx.xx.xx.xx;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtil {
public static JedisPool jedisPool = null;
// Redis服务器IP
public static String ADDR = "192.168.171.45";
// Redis的端口号
public static int PORT = 6379;
// 访问密码
// public static String AUTH = "123456";
/**
* 初始化Redis连接池
*/
static {
try {
JedisPoolConfig config = new JedisPoolConfig();
// 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
config.setBlockWhenExhausted(true);
// 设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
// 是否启用pool的jmx管理功能, 默认true
config.setJmxEnabled(true);
// 最大空闲连接数, 默认8个 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
config.setMaxIdle(8);
// 最大连接数, 默认8个
config.setMaxTotal(200);
// 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
config.setMaxWaitMillis(1000 * 100);
// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
config.setTestOnBorrow(true);
// jedisPool = new JedisPool(config, ADDR, PORT, 3000, AUTH);
jedisPool = new JedisPool(config, ADDR, PORT, 3000);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取Jedis实例
*
* @return
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 释放jedis资源
*
* @param jedis
*/
public static void close(final Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
}
创建redis存ES
package cn.xx.xx.xx.xx;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import redis.clients.jedis.Jedis;
import java.util.HashMap;
import java.util.Map;
public class SaveRedisUtils {
public static JSONObject saveRedis(SearchRequestBuilder query, Jedis jedis, Integer size, Client esClient) {
SearchResponse searchResponse = query.setScroll(TimeValue.timeValueHours(ConstantUtils.TIMEVALUE)).setSize(size).get();
SearchHits searchHits = searchResponse.getHits();
Long totals = searchHits.totalHits;
System.out.println(totals);
int jedisNumber = 0;
int expiretime = 60 * 60;
JSONObject output_result = new JSONObject();
String cacheId = DigestUtils.md5Hex(query.toString());
if (jedis.exists(cacheId)) {
jedis.expire(cacheId, expiretime);
totals = jedis.hlen(cacheId);
} else {
if (searchHits.getHits().length > 0) {
for (int i = 0; i < Math.min(totals, size); i++) {
try {
String sourceAsMap = searchHits.getHits()[i].getSourceAsString();
String redisNumber = Integer.toString(jedisNumber++);
jedis.hset(cacheId, redisNumber, sourceAsMap);
jedis.expire(cacheId, expiretime);
} catch (Exception e) {
}
}
if (totals > size) {
double page = Math.floor(totals / size);
String scrollId = searchResponse.getScrollId();
for (int j = 0; j < page; j++) {
SearchResponse rep1 = esClient.prepareSearchScroll(scrollId) //设置游标
.setScroll(TimeValue.timeValueHours(ConstantUtils.TIMEVALUE)) //设置游标有效期
.execute()
.actionGet();
Map<String, String> sourceAsMap = new HashMap<String, String>();
for (SearchHit record : rep1.getHits().getHits()) {
String redisNumber = Integer.toString(jedisNumber++);
sourceAsMap.put(redisNumber,record.getSourceAsString());
}
jedis.hmset(cacheId,sourceAsMap);
jedis.expire(cacheId, expiretime);
scrollId = rep1.getScrollId();
}
}
}
}
RedisUtil.close(jedis);
output_result.put("status", "success");
output_result.put("cacheId", cacheId);
output_result.put("total", totals);
return output_result;
}
}
创建redis存Schema
package cn.xx.xx.xx.xx;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import redis.clients.jedis.Jedis;
import java.io.IOException;
public class SaveSchemaRedis {
// @Autowired
// private RestTemplate restTemplate;
public static String getRedis(String schema, Jedis jedis) {
int expiretime = 60 * 60;
JSONObject output_result = new JSONObject();
if (jedis.exists("schema")) {
// jedis.expire("schema", expiretime);
jedis.get("schema");
System.out.println("success");
}else {
// ResponseEntity<JSONObject> tuple = restTemplate.getForEntity("http://zhao/ontologyDB/getAllOntoloyAndRelation", JSONObject.class);
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http GET请求
HttpGet httpGet = new HttpGet("http://192.168.170.152:8081/ontologyDB/getAllOntoloyAndRelation");
CloseableHttpResponse response = null;
try {
// 执行请求
// httpResponse = httpClient.execute(httpPost);
try {
response = httpclient.execute(httpGet);
} catch (IOException e) {
e.printStackTrace();
}
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
//请求体内容
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
jedis.set("schema",content);
jedis.expire("schema",expiretime);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// RedisUtil.close(jedis);
// output_result.put("schema", jedis.get("schema"));
String result = jedis.get("schema");
return result;
}
}
接口里获取数据存redis
Jedis jedis = RedisUtil.getJedis();
jedis.set("xx",result.toString());
jedis.expire("schema",3600);
接口里获取redis中存的数据
Jedis jedis = RedisUtil.getJedis();
String s = SaveSchemaRedis.getRedis("xx",jedis);
如有不当之处,欢迎指正。您的指点是我进步的捷径。
友情提示,小哥哥,打赏功能要不要试一试。