1.添加依赖

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

2.在application.properties中配置redis

#redis
redis.host=192.168.220.128
redis.port=
redis.timeout=
redis.password=
redis.poolMaxTotal=
redis.poolMaxIdle=
redis.poolMaxWait=

3.创建RedisConfig类 对应application.properties中的配置

@Component
@ConfigurationProperties(prefix="redis")
public class RedisConfig {
private String host;
private int port;
private int timeout;//秒
private String password;
private int poolMaxTotal;
private int poolMaxIdle;
private int poolMaxWait;//秒
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPoolMaxTotal() {
return poolMaxTotal;
}
public void setPoolMaxTotal(int poolMaxTotal) {
this.poolMaxTotal = poolMaxTotal;
}
public int getPoolMaxIdle() {
return poolMaxIdle;
}
public void setPoolMaxIdle(int poolMaxIdle) {
this.poolMaxIdle = poolMaxIdle;
}
public int getPoolMaxWait() {
return poolMaxWait;
}
public void setPoolMaxWait(int poolMaxWait) {
this.poolMaxWait = poolMaxWait;
}
}

4.创建RedisServer

@Service
public class RedisService { @Autowired
JedisPool jedisPool; /**
* 获取当个对象
* */
public <T> T get(KeyPrefix prefix, String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
String str = jedis.get(realKey);
T t = stringToBean(str, clazz);
return t;
}finally {
returnToPool(jedis);
}
} /**
* 设置对象
* */
public <T> boolean set(KeyPrefix prefix, String key, T value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String str = beanToString(value);
if(str == null || str.length() <= ) {
return false;
}
//生成真正的key
String realKey = prefix.getPrefix() + key;
int seconds = prefix.expireSeconds();
if(seconds <= ) {
jedis.set(realKey, str);
}else {
jedis.setex(realKey, seconds, str);
}
return true;
}finally {
returnToPool(jedis);
}
} /**
* 判断key是否存在
* */
public <T> boolean exists(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.exists(realKey);
}finally {
returnToPool(jedis);
}
} /**
* 增加值
* */
public <T> Long incr(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.incr(realKey);
}finally {
returnToPool(jedis);
}
} /**
* 减少值
* */
public <T> Long decr(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.decr(realKey);
}finally {
returnToPool(jedis);
}
} private <T> String beanToString(T value) {
if(value == null) {
return null;
}
Class<?> clazz = value.getClass();
if(clazz == int.class || clazz == Integer.class) {
return ""+value;
}else if(clazz == String.class) {
return (String)value;
}else if(clazz == long.class || clazz == Long.class) {
return ""+value;
}else {
return JSON.toJSONString(value);
}
} @SuppressWarnings("unchecked")
private <T> T stringToBean(String str, Class<T> clazz) {
if(str == null || str.length() <= || clazz == null) {
return null;
}
if(clazz == int.class || clazz == Integer.class) {
return (T)Integer.valueOf(str);
}else if(clazz == String.class) {
return (T)str;
}else if(clazz == long.class || clazz == Long.class) {
return (T)Long.valueOf(str);
}else {
return JSON.toJavaObject(JSON.parseObject(str), clazz);
}
} private void returnToPool(Jedis jedis) {
if(jedis != null) {
jedis.close();
}
} }

5.创建RedisPoolFactory

@Service
public class RedisPoolFactory { @Autowired
RedisConfig redisConfig; @Bean
public JedisPool JedisPoolFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * );
JedisPool jp = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(),
redisConfig.getTimeout()*, redisConfig.getPassword(), );
return jp;
} }

6.在controller中写一个demo

@Controller
@RequestMapping("/demo")
public class SampleController { @Autowired
UserService userService; @Autowired
RedisService redisService; @RequestMapping("/hello")
@ResponseBody
public Result<String> home() {
return Result.success("Hello,world");
} @RequestMapping("/error")
@ResponseBody
public Result<String> error() {
return Result.error(CodeMsg.SESSION_ERROR);
} @RequestMapping("/hello/themaleaf")
public String themaleaf(Model model) {
model.addAttribute("name", "Joshua");
return "hello";
} @RequestMapping("/db/get")
@ResponseBody
public Result<User> dbGet() {
User user = userService.getById();
return Result.success(user);
} @RequestMapping("/db/tx")
@ResponseBody
public Result<Boolean> dbTx() {
userService.tx();
return Result.success(true);
} @RequestMapping("/redis/get")
@ResponseBody
public Result<User> redisGet() {
User user = redisService.get(UserKey.getById, ""+, User.class);
return Result.success(user);
} @RequestMapping("/redis/set")
@ResponseBody
public Result<Boolean> redisSet() {
User user = new User();
user.setId();
user.setName("");
redisService.set(UserKey.getById, ""+, user);//UserKey:id1
return Result.success(true);
} }

详细集成Redis (一)的更多相关文章

  1. 详细介绍Redis的几种数据结构以及使用注意事项(转)

    原文:详细介绍Redis的几种数据结构以及使用注意事项 1. Overview 1.1 资料 <The Little Redis Book>,最好的入门小册子,可以先于一切文档之前看,免费 ...

  2. (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 本文章牵涉到的技术点比较多:Spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对 ...

  3. 7、Spring Boot 2.x 集成 Redis

    1.7 Spring Boot 2.x 集成 Redis 简介 继续上篇的MyBatis操作,详细介绍在Spring Boot中使用RedisCacheManager作为缓存管理器,集成业务于一体. ...

  4. Spring Boot从入门到精通(六)集成Redis实现缓存机制

    Redis(Remote Dictionary Server ),即远程字典服务,是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言 ...

  5. Spring Boot 如何快速集成 Redis 哨兵?

    上一篇:Spring Boot 如何快速集成 Redis? 前面的分享栈长介绍了如何使用 Spring Boot 快速集成 Redis,上一篇是单机版,也有粉丝留言说有没有 Redis Sentine ...

  6. Spring Boot集成Redis集群(Cluster模式)

    目录 集成jedis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 集成spring-data-redis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 异常处理 同样的, ...

  7. 【springBoot】springBoot集成redis的key,value序列化的相关问题

    使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...

  8. SpringBoot集成redis的key,value序列化的相关问题

    使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...

  9. spring集成redis

    redis是一种非关系型数据库,与mongoDB不同的是redis是内存数据库,所以访问速度很快.常用作缓存和发布-订阅式的消息队列.redis官方没有提供windows版本的软件.windows版本 ...

随机推荐

  1. heartbeat 非联网安装(通过配置本地yum文件库安装heartbeat)

    软件环境:centos6.5 一.下载rpm包 首先找一台联网的centos6.5机器 安装epel扩展源: yum install -y epel-release 安装yum-plugin-down ...

  2. krpano 常用标签

    <krpano></krpano>根标签 相当于 <body> <scene></scene>一个全景图场景 <image> 图 ...

  3. js可拖拽的div

    function chatDrag(div1) { div1.onmousedown = function (ev) { var oevent = ev || event; var distanceX ...

  4. Codeforces 396 E. Valera and Queries

    题目链接:http://codeforces.com/problemset/problem/369/E 考虑将问题转化为有多少条线段没有覆盖这些点,如果一个询问的点集是${[x1,x2,...,xn] ...

  5. JedisPubSub

    MsgListener extends JedisPubSub notify-keyspace-events "KEA"

  6. windows下用c++调用caffe做前向

    参考博客: https://blog.csdn.net/muyouhang/article/details/54773265 https://blog.csdn.net/hhh0209/article ...

  7. (转)理解CPU steal time

    转自:https://www.cnblogs.com/menkeyi/p/6732020.html Netflix 很关注CPU的Steal Time.他们的策略是:如果是当前虚拟机的Steal Ti ...

  8. angular 引入编辑器遇到的各种问题。。。

    1.项目中找不到angular-cli.json,也找不到angular.json 2. 3.

  9. Element-ui表格选中回显

    先瞄一下,是不是你要的效果 然后,废话不多说,直接上代码啦 <template> <div class> <div class="projectData&quo ...

  10. Word中如何删除目录页的页码

    ---恢复内容开始--- word中插入目录之后想要为每页添加页码,如果我们直接添加页码的话会出现目录是第一页,正文部分的页码是从2开始而不是1,用下面的方法就可以解决 首先让文档中的所有符号可见 第 ...