0、pom.xml

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>

1.配置文件

#不用 springboot的redisTemplate,所以不用Springboot自身集成的redis配置
redis:
host: localhost
port:
timeout:
passpord: xiaochao
poolMaxTotal:
poolMaxIdle:
poolMaxWait:
passport: xiaochao

2.配置项映射类

package com.everjiankang.miaosha.redis;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; import lombok.Data; @Data
@Component
@ConfigurationProperties("redis")
public class RedisConfig {
private String host;
private String username;
private String passport;
private int port;
private int timeout;
private String passpord;
private int poolMaxTotal;
private int poolMaxIdle;
private int poolMaxWait;
}

3.配置类

package com.everjiankang.miaosha.config;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.everjiankang.miaosha.redis.RedisConfig; import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; @Configuration
public class MyConfig { @Autowired
RedisConfig redisConfig; @Bean
public JedisPool jedisPoolFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);
return new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getTimeout(), redisConfig.getPasspord());
}
}

4、前缀接口

package com.everjiankang.miaosha.redis;

/**
* 前缀接口
* @author guchunchao
*
*/
public interface KeyPrefix {
/**
* 获取过期时间
* @return
*/
int expireSeconds(); /**
* 获取前缀
* @return
*/
String getPrefix();
}

5、前缀基础实现

package com.everjiankang.miaosha.redis;

public abstract class BaseKeyPrefix implements KeyPrefix{

    private int expireSeconds;

    private String prefix;

    public BaseKeyPrefix(int expireSeconds, String prefix) {
super();
this.expireSeconds = expireSeconds;
this.prefix = prefix;
} public BaseKeyPrefix(String prefix) {
this.expireSeconds = 0;
this.prefix = prefix;
} @Override
public int expireSeconds() { //默认0代表永不过期
return expireSeconds;
} @Override
public String getPrefix() {
String className = getClass().getSimpleName();
return className + ":" + prefix;
}
}

6、前缀实现类

package com.everjiankang.miaosha.redis;

public class UserKey extends BaseKeyPrefix {

    private UserKey(int expireSeconds, String prefix) {
super(expireSeconds, prefix);
} private UserKey(String prefix) {
super(prefix);
} public static UserKey getById = new UserKey("id");
public static UserKey getByName = new UserKey("name"); }

7、Jedis操作Redis类:

package com.everjiankang.miaosha.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; @Service
public class RedisService { @Autowired
JedisPool jedisPool; /**
* 获取单个对象
* @param prefix
* @param key
* @param clazz
* @return
*/
public <T> T get(KeyPrefix prefix,String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String realKey = prefix.getPrefix() + key;
String value = jedis.get(realKey);
T t = stringToBean(value,clazz);
return t;
} finally {
returnToPool(jedis);
}
} /**
* 设置对象
* @param prefix
* @param key
* @param value
* @return
*/
public boolean set(KeyPrefix prefix, String key, Object value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String str = beanToString(value);
if(str == null || str.length() <=0)
return false;
int expireSecond = prefix.expireSeconds();
String realKey = prefix.getPrefix() + key;
if(expireSecond <= 0) {
jedis.set(realKey,str);
} else {
jedis.setex(realKey, expireSecond, str);
}
return true;
} finally {
returnToPool(jedis);
}
} /**
* 判断是否存在
* @param prefix
* @param key
* @return
*/
public boolean exist(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String realKey = prefix.getPrefix() + key;
return jedis.exists(realKey);
} finally {
returnToPool(jedis);
}
} /**
* 增加
* @param prefix
* @param key
* @param clazz
* @return
*/
public <T> Long incri(KeyPrefix prefix,String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String realKey = prefix.getPrefix() + key;
Long incr = jedis.incr(realKey);
return incr;
} finally {
returnToPool(jedis);
}
} /**
* 减少
* @param prefix
* @param key
* @param clazz
* @return
*/
public <T> Long decr(KeyPrefix prefix,String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String realKey = prefix.getPrefix() + key;
Long decr = jedis.decr(realKey);
return decr;
} finally {
returnToPool(jedis);
}
} /**
* Java对象转String
* @param value
* @return
*/
private <T> String beanToString(T value) {
if(value == null)
return null;
Class<?> clazz = value.getClass(); if(clazz == int.class || clazz == Integer.class
|| clazz == long.class || clazz == Long.class
|| clazz == float.class || clazz == Float.class
|| clazz == double.class || clazz == Double.class
)
return "" + value;
else if(value instanceof String)
return (String) value;
else
return JSON.toJSONString(value); } /**
* string 转Java
* @param value
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
private <T> T stringToBean(String value,Class<T> clazz) {
if(value == null)
return null;
if(clazz == int.class || clazz == Integer.class)
return (T) Integer.valueOf(value);
else if( clazz == long.class || clazz == Long.class)
return (T) Long.valueOf(value);
else if(clazz == float.class || clazz == Float.class)
return (T) Float.valueOf(value);
else if(clazz == double.class || clazz == Double.class)
return (T) Double.valueOf(value);
else if(value instanceof String)
return (T) value;
else
return JSON.toJavaObject(JSON.parseObject(value), clazz);
} /**
* 将Jedis链接还回连接池:详情close方法
* @param jedis
*/
private void returnToPool(Jedis jedis) {
if(jedis != null)
jedis.close();
}
}

8、controller调用实例

package com.everjiankang.miaosha.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.everjiankang.miaosha.model.CodeMsg;
import com.everjiankang.miaosha.model.Result;
import com.everjiankang.miaosha.model.User;
import com.everjiankang.miaosha.redis.RedisService;
import com.everjiankang.miaosha.redis.UserKey;
import com.everjiankang.miaosha.service.UserService; @Controller
@RequestMapping("/test")
public class TestController { @Autowired
UserService userService; @Autowired
RedisService redisService; @PostMapping("/test01")
@ResponseBody
public Result<String> test01() {
return Result.success("hello world");
} @PostMapping("/helloError")
@ResponseBody
public Result<String> helloError() {
return Result.error(CodeMsg.SERVER_ERROR);
} @RequestMapping("/thymeleaf")
public String thymeleaf() {
return "thymeleaf";
} @RequestMapping("/getById/{id}")
@ResponseBody
public Result<User> getById(@PathVariable("id") int id) {
return Result.success(userService.selectByPrimaryKey(id));
} @RequestMapping("/redisGet/{key}")
@ResponseBody
public Result<String> redisGet(@PathVariable("key") String key) {
String string = redisService.get(UserKey.getById,key, String.class);
return Result.success(string);
} @RequestMapping("/redisSet/{key}/{value}")
@ResponseBody
public Result<String> redisSet(@PathVariable("key") String key,@PathVariable("value") String value) {
if(key != null && !"".equals(key.trim()) && value != null && !"".equals(value)) {
boolean result = redisService.set(UserKey.getById,key, value);
if(result)
return Result.success(redisService.get(UserKey.getById,key, String.class));
else
return Result.error(CodeMsg.SERVER_ERROR);
} else {
return Result.error(CodeMsg.SERVER_ERROR);
}
} @RequestMapping("/redisSetUserTest")
@ResponseBody
public Result<User> redisSetUserTest(@PathVariable("key") String key) {
User user = new User();
user.setId(1);
user.setAge(27);
user.setName("xiaochao");
user.setSex(1);
boolean result = redisService.set(UserKey.getById,key, user);
if(result)
return Result.success(user);
else
return Result.error(CodeMsg.SERVER_ERROR);
} @RequestMapping("/redisSetUserTest")
@ResponseBody
public Result<User> redisGetUserTest(@PathVariable("id") String id) { User user = redisService.get(UserKey.getById,id,User.class);
if(user != null)
return Result.success(user);
else
return Result.error(CodeMsg.SERVER_ERROR);
} }

最新文章

  1. flash与js交互
  2. 重置svn地址
  3. BFS、DFS与选课问题(拓扑排序)
  4. [iOS dispatch_once创建单例]
  5. The Beatles-Hey Jude
  6. Positive-definite matrix
  7. No.012:Integer to Roman
  8. System.Net.Sockets.Socket SendAsync System.ObjectDisposedException: Cannot access a disposed object.
  9. 使用easyUI 创建复杂的toolbar到datagrid
  10. 【渗透测试学习平台】 web for pentester -1.介绍与安装
  11. 南桥先生谈《OUTLIERS》
  12. 获取context path或者basePath
  13. 数据结构C语言版 弗洛伊德算法实现
  14. 安装ecshop的问题处理
  15. Python Mongodb接口
  16. 使用Phabricator进行代码审查
  17. Linux 小知识翻译 - 「packet」(网络数据包)
  18. CentOS 7源码安装zabbix
  19. 【转】内存分析工具 MAT 的使用
  20. 设置树莓派SSH连接因超时闲置断开(转)

热门文章

  1. 周末班:Python基础之网络编程
  2. Windows Service 学习系列(一):建立简单的Windows service
  3. Kafka 0.11.0.0 实现 producer的Exactly-once 语义(中文)
  4. 网络流 之 dinic算法
  5. Netstat 常用命令--备忘录
  6. SkylineGlobe7.0.1版本 支持SQLite(*.sqlite;*.db)数据库
  7. SQL分组求每组最大值问题的解决方法收集 (转载)
  8. lombook安装以及在eclipse和idea上配置
  9. 阿里面试题BIO和NIO数量问题附答案和代码
  10. 【Swift 3.0】iOS 国际化切换语言