数据库
首页 > 数据库> > 【Redis】07-使用SpringData-redis

【Redis】07-使用SpringData-redis

作者:互联网

1、导入依赖

<dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.4.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.4.2.RELEASE</version>

    </dependency>

2、redis配置xml

<!--配置连接池-->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!--最大连接数-->
        <property name="maxTotal" value="50"></property>
        <property name="maxIdle" value="5"></property>
    </bean>
    <!--Spring整合Jedis(Redis)-->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="ip"></property>
        <property name="port" value="port"></property>
        <property name="password" value="pwd"></property>
        <!--自定义连接池配置-->
        <property name="poolConfig" ref="jedisPoolConfig"></property>
    </bean>
    <!--redis 模板-->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"></property>
    </bean>

3、redis service

@Service
public interface UserService {
    /**
     * STRING 存取 测试
     */
    public String getString(String key);
}

3、serviceimpl

/**
 * @author AnQi
 * @date 2020/3/13 23 47:05
 * @description
 */
@Service
public class UserServiceImpl  implements UserService {

    @Autowired
    RedisTemplate<String,String> redisTemplate;
    /**
     * 通过某个key获取值
     * 若key不存在 则 再数据库中查询
     * 存在 则再redis中查询
     * @param key
     * @return
     */
    public String getString(String key) {

        ValueOperations<String, String> vo = redisTemplate.opsForValue();

        if(redisTemplate.hasKey(key)){
            //redis取
            System.out.println("redis取");
            return vo.get(key);
        }else{
            //db
            String result = "Redis模板练习";
            vo.set(key,result);
            System.out.println("数据库返回"+result);
            return result;
        }
    }
}

标签:SpringData,redis,Redis,result,key,public,redisTemplate,String
来源: https://blog.csdn.net/ange2000561/article/details/104858278