springboot + redis缓存使用

duanwu 2017-12-01 原文

springboot + redis缓存使用

【参照资料】

  1.spring boot 官网文档

  2.https://www.cnblogs.com/gdpuzxs/p/7222309.html

【项目结构】

  

 

【pom.xml配置】

<?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>lzf.test</groupId>
 <artifactId>demo.rediscache</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>demo.rediscache</name>
 <description>Demo project for Spring Boot</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.5.9.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>
 </properties>

 <dependencies>
 
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-cache</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter</artifactId>
   <exclusions>
    <exclusion>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
   </exclusions>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-log4j2</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>

【application.properties配置】

  

spring.cache.type = redis
spring.cache.cache-names=cache1
#spring.cache.redis.
spring.redis.database=0 
# Redis服务器地址
spring.redis.host=192.168.6.88
# Redis服务器连接端口
spring.redis.port=6379 
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8 
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1 
# 连接池中的最大空闲连接
spring.redis..pool.max-idle=8 
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0 
# 连接超时时间(毫秒)
spring.redis.timeout=0
spring.cache.redis.time-to-live=600000

## LOG4J配置
log4j.rootCategory=DEBUG,stdout
## 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L – %m%n

 

【相关java文件】

  【Application.java】

     

package lzf.test.demo.rediscache;

import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import lzf.test.demo.rediscache.entity.User;
import lzf.test.demo.rediscache.service.OperateUser;

@SpringBootApplication
@RestController
@EnableScheduling
@EnableCaching
public class Application {

 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
 }
 
 
 @Autowired
 private RedisCacheManager redisCacheManager;
 @Autowired
 private StringRedisTemplate stringRedisTemplate;
 @Autowired
 private OperateUser operateUser;
 @Autowired
 private RedisTemplate redisTemplate;
 
 @RequestMapping(“/age/{age}”)
 public String testRedis(@PathVariable String age){
  ValueOperations<String, String> ops =stringRedisTemplate.opsForValue();
  
  ops.set(“bbb”, age);
  RedisConnection connection = stringRedisTemplate.getConnectionFactory().getConnection();
  List<String> config = connection.getConfig(“hostname”);
  //————————–
  
  Collection<String> cacheNames = redisCacheManager.getCacheNames();
  Cache cache = null;
  for(String s : cacheNames){
   cache = redisCacheManager.getCache(s);
   
  }
  return age; 
  
 }
 /**
  * TODO 查询缓存
  * @author 刘宗峰
  * @param username
  * @return
  */
 @RequestMapping(“/user/{username}”)
 @ResponseBody
 public List<User> findUsers(@PathVariable String username){
  ValueOperations opsForValue = redisTemplate.opsForValue();
  Set keys = redisTemplate.keys(“*wang5*”.getBytes());
  for(Object key : keys){
   System.out.println(key.toString());
  }
  List<User> us = operateUser.findUser(username);
  return us;
  
 }
 /**
  * TODO 删除时清理缓存
  * @author 刘宗峰
  * @param username
  * @return
  */
 @RequestMapping(“/del/{username}”)
 public String delUser(@PathVariable String username){
  
  operateUser.delUser(username);
  return “success”;
 }
 
 @RequestMapping(“/update/{username}/{age}”)
 public String updateUser(@PathVariable String username,@PathVariable Integer age){
  operateUser.updateUser(username, age);
  ValueOperations opsForValue = redisTemplate.opsForValue();
  Set keys = opsForValue.getOperations().keys(“*wang5*”);
  for(Object key : keys){
   System.out.println(key.toString());
  }
  System.out.println(opsForValue.get(username));
  return “success”;
 }
}

   【OperateUser.java】

    

package lzf.test.demo.rediscache.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;

import lzf.test.demo.rediscache.entity.User;
@Service
@CacheConfig(cacheNames = “cache1”)
public class OperateUser {

 //1.查询user @Cacheable将查询结果缓存到redis中,(key=”#p0″)指定传入的第一个参数作为redis的key
 @Cacheable(key =”#p0″)
 public List<User> findUser(@Param(“username”) String username){
  
  List<User> us = new ArrayList<User>();
  User u1 = new User(“wang5”,12);
  //User u2 = new User(“zhao6”,15);
  
  us.add(u1);
  //us.add(u2);
  
  return us;
 }
 //如果指定为 true,则方法调用后将立即清空所有缓存
 @CacheEvict(key =”#p0″,allEntries=true)
 public void delUser(@Param(“username”) String username){
  //
 }
 @CachePut(key = “#p0”)
 public List<User> updateUser(@Param(“username”) String username,Integer age){
  List<User> us = new ArrayList<User>();
  User u1 = new User(username,age);
  us.add(u1);
  return us;
 }
}

—————————————————————————

缓存使用的没问题。但是想要手动操作数据,但是没能取出key–value

 

发表于 2017-12-01 15:36 端午节后4天 阅读() 评论() 编辑 收藏

 

版权声明:本文为duanwu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:http://www.cnblogs.com/duanwu/p/7942703.html

springboot + redis缓存使用的更多相关文章

  1. docker + springboot + springColud 下,项目中有配置文件,读取出现file not found 路径中有!的问题

    最近在做微信支付的开发,做到退款的时候,需要使用到p12 证书,在本地调试没问题了,打成jar 包,放入到do […]...

  2. 玩转 SpringBoot 2 快速搭建 | RESTful Api 篇

    玩转 SpringBoot 2 快速搭建 | RESTful Api 篇 概述 RESTful 是一种架构风格 […]...

  3. springboot集成redis(mybatis、分布式session)

    springboot集成redis(mybatis、分布式session) Posted on 2018-04 […]...

  4. springboot情操陶冶-web配置(二)

    承接前文springboot情操陶冶-web配置(一),在分析mvc的配置之前先了解下其默认的错误界面是如何显 […]...

  5. 12、SpringBoot——activeMq的简单使用

    开发工具:STS 前言:   What is ActiveMq?   ActiveMq:实现了Jms规范的一款 […]...

  6. [springboot 开发单体web shop] 8. 商品详情&评价展示

    上文回顾 上节 我们实现了根据搜索关键词查询商品列表和根据商品分类查询,并且使用到了mybatis-pageh […]...

  7. SpringBoot 整合 MyBatis-Plus 入门体验

    一、前言 本文小编将基于 SpringBoot 整合 MyBatis-Plus , MyBatis-Plus […]...

  8. Eclipse+Spring boot+集成Druid连接池(MySQL8.0.11)

    今天看到MYSQL 新版的消息。据说8.0的版本比5系列速度快2倍 所以就把本地的升级到8.0.11,Ecli […]...

随机推荐

  1. SmartSql使用教程(2)—使用动态代理实现CURD

    一、引言   接着上一篇的教程,本章我们继续讲SmartSql。今天的主题是动态仓储。   老规矩,先上一个项 […]...

  2. 7.2_securecrt使用教程、SecureCRT配置详细图文教程

      Secure CRT是一款支持 SSH2、SSH1、Telnet、Telnet/SSH、Relogin、S […]...

  3. webpack(6)webpack处理图片

    图片处理url-loader(webpack5之前的处理方式) 在项目开发中,我们时长会需要使用到图片,比如在 […]...

  4. 零基础数据挖掘学习清单

    先甩片汤话:不知怎么的,就从纯工科的学业到管理工作岗位,又进入了数据挖掘的学习。一切都是从头学起,不会写代码, […]...

  5. Python3 与 C# 面向对象之~异常相关

    周末多码文,昨天晚上一篇,今天再来一篇: 在线编程:https://mybinder.org/v2/gh/lo […]...

  6. 【tf.keras】tf.keras加载AlexNet预训练模型

    tf.keras 的预训练模型都放在了’tensorflow.python.keras.appli […]...

  7. 网站制作流程 域名注册篇

    话说今天Mr.王创建了一个公司 当务之急是宣传问题 于是Mr.王瞄准拥有7.6亿网民的互联网市场 那么建立自己 […]...

  8. 软件License设计 常见加密算法简析

    如何保护软件版权,最常用的办法就是设计一套license验证框架。 1、我们的常规需求如下: 1.可以限制软件 […]...

展开目录

目录导航