您的位置:首页 > 数据库 > Redis

Redis~redis+springboot的demo

2018-01-11 16:44 399 查看

Redis说明

redis是一个key-value库,在java中的使用,作为小型数据的缓存比较常见。

比如,管理员实现角色分配权限时,每次操作时都会执行很多查询,这样会影响效率。怎么提升程序性能呢?我们可以考虑用缓存数据库来实现。

代码下载地址

https://github.com/weiaiwan/redisdemo

创建项目

创建springboot项目时勾选



勾选后项目会自动导入jar



使用redis缓存有三步

1、配置application.properties中的redis

#springboot+mybatis
#加载mybatis配置
mybatis.config-location=classpath:mapper/config/mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*.xml

#数据源
spring.datasource.url=jdbc:mysql://120.199.82.51:3062/px_user?useUnicode=true&characterEncoding=UTF-8
#数据源驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root

#redis
spring.redis.host=127.0.0.1
spring.redis.port=6379


2、在启动项目类上加@EnableCaching

package com.example.redisdemo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@MapperScan("com.example.redi
4000
sdemo.dao")//加载dao
@EnableCaching//redis
public class RedisdemoApplication {

public static void main(String[] args) {
SpringApplication.run(RedisdemoApplication.class, args);
}
}


3、在serviceImpl类上加@Cacheable

@Cacheable 注解表示在 redis 缓存区域开启了一个名称空间叫 userCount 的缓存,userCount 中就是存储着查询的数据。当第二次访问时,它首先会先在缓存中寻找数据,如果有则直接返回缓存,没有再访问数据库。

@Override
@Cacheable(value="userCount")
public int getUserpCount() {
// TODO Auto-generated method stub
System.out.println("------走这了-------");
return userMapper.getUserpCount();
}


第一次访问,控制台会输出“———走这了———–”

第二次访问发现不会走,但扔输出数据,证明缓存成功。

@Cacheable(cacheNames, key )的用法

创建一个key为* 的缓存数据

自定义策略是指我们可以通过Spring的EL表达式来指定我们的key。这里的EL表达式可以使用方法参数及它们对应的属性。使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。

例1:

由于此方法使用缓存,并且返回值是User对象,那么User必须实现序列化接口。

@Override
@Cacheable(cacheNames = "product", key = "#map.get('id')")
public User getUserp(Map<String, Object> map) {
System.out.println("成功");
return userDao.getUserp(map);
}


public class User implements Serializable{

/**
* redis缓存User 必须序列化
*/
private static final long serialVersionUID = 2763505794811845071L;


否则会报错:



其他例子:

@Cacheable(value="users", key="#id")

public User find(Integer id) {

returnnull;

}

@Cacheable(value="users", key="#p0")

public User find(Integer id) {

returnnull;

}

@Cacheable(value="users", key="#user.id")

public User find(User user) {

returnnull;

}

@Cacheable(value="users", key="#p0.id")

public User find(User user) {

returnnull;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: