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. SpringBoot入坑-项目搭建

      对于学过三大框架的小童鞋,从今天开始给大家带来一套新的框架学习,相信对于做程序的小童鞋一定有所耳闻,作为下 […]...

  2. springboot-mybatis 批量insert

    springboot mybatis 批量insert 操作 直接上代码: 1.首先要在pom.xml中导入包 […]...

  3. Springboot 2.0.x 集成基于Centos7的Redis集群安装及配置

    Redis简介 Redis是一个基于C语言开发的开源(BSD许可),开源高性能的高级内存数据结构存储,用作数据 […]...

  4. 七、springBoot 简单优雅是实现文件上传和下载

    前言 好久没有更新spring Boot 这个项目了。最近看了一下docker 的知识,后期打算将spring […]...

  5. Springboot-Listener(springboot的事件监听的4种实现方式)

    springboot事件监听的4种方式 第1种:    1.自定义事件MyApplicationEvent继承 […]...

  6. springboot上传文件控制文件大小

    最近做项目需要开发一个通过excel表格导入数据的功能,上传接口写好调试的时候遇到几个问题,记录一下。 报错1 […]...

  7. SpringBoot整合JSP(毕设亲测可用)

     因为,临近毕业了,自己虽然也学了很多框架。但是,都是在别人搭建好的基础上进行项目开发。但是springboo […]...

  8. SpringBoot 2.x版本+MultipartFile设置指定文件上传大小

    SpringBoot-versio:2.1.9-RELEASE   由于新版本的SpringBoot已经弃用了 […]...

随机推荐

  1. for-of循环

      for (var value of myArray) { console.log(value); } 是的 […]...

  2. Nvidia驱动正确安装过程

      找到适合的正确的驱动 去nvidia驱动官网下载 卸载掉原有驱动 sudo apt-get remove […]...

  3. Oracle_用户-授权-角色

    Oracle创建用户及表空间 1. 用户 创建用户: sql> create user <用户名& […]...

  4. 手把手教你使用python开发植物大战僵尸游戏

    手把手教你使用python开发植物大战僵尸游戏 课程目标 1.掌握python面向对象编程思想 2.熟练pyt […]...

  5. 模型的性能评估(二) 用sklearn进行模型评估

    在sklearn当中,可以在三个地方进行模型的评估 1:各个模型的均有提供的score方法来进行评估。 这种方 […]...

  6. 如何在 Mac 上录制视频

    使用 QuickTime Player 在 Mac 上录制视频 QuickTime Player 是 Quic […]...

  7. java面试题-Java集合相关

    1. ArrayList 和 Vector 的区别   ArrayList和Vector底层实现原理都是一样得 […]...

  8. 如何在windows上玩转redis的最新特性?

    想要了解redis的最新特性,可是windows下的可以安装的版本最高为3.2,想要验证redis的诸如str […]...

展开目录

目录导航