1.引入maven依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2.在application.properties里面配置地址
spring.redis.host=192.168.3.4
spring.redis.port=6379
spring.redis.database=0
3.在config文件中配置RedisConfig
import com.hourui.util.RedisUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RedisConfig {
//读取配置文件中的redis的ip地址
@Value("${spring.redis.host:disabled}")
private String host;
@Value("${spring.redis.port:0}")
private int port;
@Value("${spring.redis.database:0}")
private int database;
@Bean
public RedisUtil getRedisUtil() {
if (host.equals("disabled")) {
return null;
}
RedisUtil redisUtil = new RedisUtil();
redisUtil.initPool(host, port, database);
return redisUtil;
}
}
4.在util文件中配置RedisUtil
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtil {
private JedisPool jedisPool;
public void initPool(String host,int port ,int database){
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(200);
poolConfig.setMaxIdle(30);
poolConfig.setBlockWhenExhausted(true);
poolConfig.setMaxWaitMillis(10*1000);
poolConfig.setTestOnBorrow(true);
jedisPool=new JedisPool(poolConfig,host,port,20*1000);
}
public Jedis getJedis(){
Jedis jedis = jedisPool.getResource();
return jedis;
}
}
5.注入RedisUtil,然后使用
@Service
public class CartServiceImpl implements CartService {
@Autowired
RedisUtil redisUtil;
@Override
public void addCart(OmsCartItem omsCartItem) {
cartItemMapper.insertSelective(omsCartItem);
// 同步redis缓存
Jedis jedis = redisUtil.getJedis();
jedis.hset("user:"+omsCartItem.getMemberId()+":cart",omsCartItem.getId(), JSON.toJSONString(omsCartItem));
jedis.close();
}
}