1 redis 整合
1.1 导入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
1.2 配置文件
server:
port: 9006
spring:
application:
name: boot-user
redis:
host: 192.168.85.198
database: 0
port: 6379
timeout: 2000
password:
lettuce: //springboot 2.0 以后不在使用jedis 作为客户端 使用lettuce为底层
pool:
max-active: 20 //最大连接数
max-wait: -1 // 最大阻塞等待时间 -1 表示没有限制
max-idle: 8 // 最大连接池空闲数量
min-idle: 0 // 表示最小空闲连接数量
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.85.198:3306/tensquare_user?
characterEncoding=utf-8&&useSSL=false
username: root
password: 123456
jpa:
database: mysql
show-sql: true
generate-ddl: true
1.3 使用实例
package com.liu.user.service;
import com.liu.common.entity.PageResult;
import com.liu.user.dao.UserDao;
import com.liu.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by Administrator on 2019/8/15 0015.
*/
@Service
@Slf4j
public class UserService {
package com.liu.user.service;
import com.liu.common.entity.PageResult;
import com.liu.user.dao.UserDao;
import com.liu.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by Administrator on 2019/8/15 0015.
* @service 用来标准他是一个service层的实现类
* @Slf4j 用来生成一个log的内置对象,这样我们就可以使用log 来记录日志
*
*/
@Service
@Slf4j
public class UserService {
@Autowired
private RedisTemplate redisTemplate ;
@Autowired
private UserDao userDao;
public User findById(String id){
User user = (User) redisTemplate.opsForValue().get("user_"+id);
if(user ==null){
log.info("缓存中无数据 {}",user);
user =userDao.findById(id).get();
redisTemplate.opsForValue().set("user_"+id,user);
}
return user;
}
public PageResult findAllByPage(int page, int rows, String query){
Pageable pageable= PageRequest.of(page-1,rows);
log.info("query:{}",query);
Page<User> users = userDao.findSearch(query,pageable);
log.info("{}",users.getContent());
return new PageResult(users.getTotalElements(),users.getContent());
}
}
@Autowired
private RedisTemplate redisTemplate ;
@Autowired
private UserDao userDao;
public User findById(String id){
User user = (User) redisTemplate.opsForValue().get("user_"+id);
if(user ==null){
log.info("缓存中无数据 {}",user);
user =userDao.findById(id).get();
redisTemplate.opsForValue().set("user_"+id,user);
}
return user;
}
}