JsonUtils
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.util.List;
import java.util.Map;
public class JsonUtils {
/**
* <pre>
* 对象转化为json字符串
*
* @param obj 待转化对象
* @return 代表该对象的Json字符串
*/
public static final String toJson(final Object obj) {
return JSON.toJSONString(obj);
// return gson.toJson(obj);
}
/**
* <pre>
* 对象转化为json字符串
*
* @param obj 待转化对象
* @return 代表该对象的Json字符串
*/
public static final String toJson(final Object obj, SerializerFeature... features) {
return JSON.toJSONString(obj, features);
// return gson.toJson(obj);
}
/**
* 对象转化为json字符串并格式化
*
* @param obj
* @param format 是否要格式化
* @return
*/
public static final String toJson(final Object obj, final boolean format) {
return JSON.toJSONString(obj, format);
}
/**
* 对象对指定字段进行过滤处理,生成json字符串
*
* @param obj
* @param fields 过滤处理字段
* @param ignore true做忽略处理,false做包含处理
* @param features json特征,为null忽略
* @return
*/
public static final String toJson(final Object obj, final String[] fields, final boolean ignore,
SerializerFeature... features) {
if (fields == null || fields.length < 1) {
return toJson(obj);
}
if (features == null)
features = new SerializerFeature[] {
SerializerFeature.QuoteFieldNames };
return JSON.toJSONString(obj, new PropertyFilter() {
@Override
public boolean apply(Object object, String name, Object value) {
for (int i = 0; i < fields.length; i++) {
if (name.equals(fields[i])) {
return !ignore;
}
}
return ignore;
}
}, features);
}
/**
* <pre>
* 解析json字符串中某路径的值
*
* @param json
* @param path
* @return
*/
@SuppressWarnings("unchecked")
public static final <E> E parse(final String json, final String path) {
String[] keys = path.split(",");
JSONObject obj = JSON.parseObject(json);
for (int i = 0; i < keys.length - 1; i++) {
obj = obj.getJSONObject(keys[i]);
}
return (E) obj.get(keys[keys.length - 1]);
}
/**
* <pre>
* json字符串解析为对象
*
* @param json 代表一个对象的Json字符串
* @param clazz 指定目标对象的类型,即返回对象的类型
* @return 从json字符串解析出来的对象
*/
public static final <T> T parse(final String json, final Class<T> clazz) {
return JSON.parseObject(json, clazz);
}
/**
* <pre>
* json字符串解析为对象
*
* @param json json字符串
* @param path 逗号分隔的json层次结构
* @param clazz 目标类
*/
public static final <T> T parse(final String json, final String path, final Class<T> clazz) {
String[] keys = path.split(",");
JSONObject obj = JSON.parseObject(json);
for (int i = 0; i < keys.length - 1; i++) {
obj = obj.getJSONObject(keys[i]);
}
String inner = obj.getString(keys[keys.length - 1]);
return parse(inner, clazz);
}
/**
* 将制定的对象经过字段过滤处理后,解析成为json集合
*
* @param obj
* @param fields
* @param ignore
* @param clazz
* @param features
* @return
*/
public static final <T> List<T> parseArray(final Object obj, final String[] fields, boolean ignore,
final Class<T> clazz, final SerializerFeature... features) {
String json = toJson(obj, fields, ignore, features);
return parseArray(json, clazz);
}
/**
* <pre>
* 从json字符串中解析出一个对象的集合,被解析字符串要求是合法的集合类型
* (形如:["k1":"v1","k2":"v2",..."kn":"vn"])
*
* @param json - [key-value-pair...]
* @param clazz
* @return
*/
public static final <T> List<T> parseArray(final String json, final Class<T> clazz) {
return JSON.parseArray(json, clazz);
}
/**
* <pre>
* 从json字符串中按照路径寻找,并解析出一个对象的集合,例如:
* 类Person有一个属性name,要从以下json中解析出其集合:
* {
* "page_info":{
* "items":{
* "item":[{"name":"KelvinZ"},{"name":"Jobs"},...{"name":"Gates"}]
* }
* }
* 使用方法:parseArray(json, "page_info,items,item", Person.class),
* 将根据指定路径,正确的解析出所需集合,排除外层干扰
*
* @param json json字符串
* @param path 逗号分隔的json层次结构
* @param clazz 目标类
* @return
*/
public static final <T> List<T> parseArray(final String json, final String path, final Class<T> clazz) {
String[] keys = path.split(",");
JSONObject obj = JSON.parseObject(json);
for (int i = 0; i < keys.length - 1; i++) {
obj = obj.getJSONObject(keys[i]);
}
String inner = obj.getString(keys[keys.length - 1]);
List<T> ret = parseArray(inner, clazz);
return ret;
}
/**
* <pre>
* 有些json的常见格式错误这里可以处理,以便给后续的方法处理
* 常见错误:使用了\" 或者 "{ 或者 }",腾讯的页面中常见这种格式
*
* @param invalidJson 包含非法格式的json字符串
* @return
*/
public static final String correctJson(final String invalidJson) {
String content = invalidJson.replace("\\\"", "\"").replace("\"{", "{").replace("}\"", "}");
return content;
}
/**
* 格式化Json
*
* @param json
* @return
*/
public static final String formatJson(String json) {
Map<?, ?> map = (Map<?, ?>) JSON.parse(json);
return JSON.toJSONString(map, true);
}
/**
* 获取json串中的子json
*
* @param json
* @param path
* @return
*/
public static final String getSubJson(String json, String path) {
String[] keys = path.split(",");
JSONObject obj = JSON.parseObject(json);
for (int i = 0; i < keys.length - 1; i++) {
obj = obj.getJSONObject(keys[i]);
System.out.println(obj.toJSONString());
}
return obj != null ? obj.getString(keys[keys.length - 1]) : null;
}
}
JsonUtil
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public abstract class JsonUtil {
private static final ObjectMapper objectMapper = new ObjectMapper();
public JsonUtil() {
}
public static final Map<String, Object> json2Map(String json) {
if (json == null) {
return null;
} else {
try {
return (Map)objectMapper.readValue(json, Map.class);
} catch (Exception var2) {
throw new RuntimeException(var2);
}
}
}
public static String map2Json(Map<String, Object> map) {
return obj2Json(map);
}
public static final <T> T json2Obj(String content, Class<T> clazz) {
if (StringUtils.isBlank(content)) {
return null;
} else {
try {
return objectMapper.readValue(content, clazz);
} catch (Exception var3) {
throw new RuntimeException(var3);
}
}
}
public static String obj2Json(Object obj) {
if (obj == null) {
return null;
} else {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException var2) {
throw new RuntimeException(var2);
}
}
}
public static <T> T fromJson(String jsonString, JavaType javaType) {
try {
return objectMapper.readValue(jsonString, javaType);
} catch (Exception var3) {
throw new RuntimeException(var3);
}
}
static {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
}
}
发起请求有如下几种方式:jdk自带的HttpUrlConnection、Apache的HttpClient(须导包org.apache.httpcomponents.httpclient )、OkHttp3
对它们封装的有RestTemplate、Feign等。
Apache的HttpClient
导包:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
工具类
package com.screen.utils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtil {
/**
* @Description: 带参数GET请求
* @Param: [url, param]
* @Return: java.lang.String
*/
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* @Description: 带参数和请求头的GET请求
* @Param: [url, param, header]
* @Return: java.lang.String
*/
public static String doGet(String url, Map<String, String> param, Map<String, String> header) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key).toString());
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
if (header != null) {
for (String key : header.keySet()) {
httpGet.setHeader(key, header.get(key).toString());
}
}
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* @Description: 无参GET请求
* @Param: [url]
* @Return: java.lang.String
*/
public static String doGet(String url) {
return doGet(url, null);
}
/**
* @Description: application/x-www-form-urlencoded编码方式带参POST请求
* @Param: [url, param]
* @Return: java.lang.String
*/
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* @Description: application/x-www-form-urlencoded编码方式带参数和请求头的POST请求
* @Param: [url, param, header]
* @Return: java.lang.String
*/
public static String doPost(String url, Map<String, String> param, Map<String, String> header) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
//添加请求头信息
if (header != null) {
for (String key : header.keySet()) {
httpPost.setHeader(key, header.get(key).toString());
}
}
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* @Description: application/x-www-form-urlencoded编码方式无参POST请求
* @Param: [url]
* @Return: java.lang.String
*/
public static String doPost(String url) {
return doPost(url, null);
}
/**
* @Description: application/json编码方式POST请求
* @Param: [url, json]
* @Return: java.lang.String
*/
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* @Description: application/json编码方式带请求头POST请求
* @Param: [url, json, header]
* @Return: java.lang.String
*/
public static String doPostJson(String url, String json, Map<String, String> header) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
//添加请求头信息
if (header != null) {
for (String key : header.keySet()) {
httpPost.setHeader(key, header.get(key).toString());
}
}
// 创建请求内容
StringEntity entity = new StringEntity(json, "utf-8");
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
}
RedisUtils
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key,long time){
try {
if(time>0){
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key){
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String ... key){
if(key!=null&&key.length>0){
if(key.length==1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
//============================String=============================
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public Object get(String key){
return key==null?null:redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key,Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key,Object value,long time){
try {
if(time>0){
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}else{
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//================================Map=================================
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key,String item){
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map<Object,Object> hmget(String key){
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String,Object> map){
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String,Object> map, long time){
try {
redisTemplate.opsForHash().putAll(key, map);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key,String item,Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key,String item,Object value,long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item){
redisTemplate.opsForHash().delete(key,item);
}
/**
* 判断hash表中是否有该项的值
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item){
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item,-by);
}
//============================set=============================
/**
* 根据key获取Set中的所有值
* @param key 键
* @return
*/
public Set<Object> sGet(String key){
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key,Object value){
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object...values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key,long time,Object...values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if(time>0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
* @param key 键
* @return
*/
public long sGetSetSize(String key){
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object ...values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//===============================list=================================
/**
* 获取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;
}
}
/**
* 获取list缓存的长度
* @param key 键
* @return
*/
public long lGetListSize(String key){
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key,long index){
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index,Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key,long count,Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
public class IpUtil {
public static String getIp(HttpServletRequest request){
String ip=request.getHeader("x-forwarded-for");
if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
ip=request.getHeader("Proxy-Client-IP");
}
if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
ip=request.getHeader("WL-Proxy-Client-IP");
}
if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
ip=request.getHeader("X-Real-IP");
}
if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
ip=request.getRemoteAddr();
}
return ip;
}
}