.NET平台下Redis使用(三)【ServiceStack.Redis学习】
阅读原文时间:2021年04月20日阅读:1

MVC4项目下对redis进行增删该查

Models文件下实体类:

public class Book
    {
        public string BookName {get;set;}
        public string Author {get;set;}
        public string Edition {get;set;}
        public string Publisher {get;set;}
        public string Summary { get; set; }
        public long Id { get; set; }
        public int InStock { get; set; }
    }

 public class Person
    { 
        public int Id { get; set; }
        public string Name { get; set; }
    }

BookService.cs代码:

 public class BookService : Service
    {
        public IRepository Repository { get; set; }

        public object Post(AddBook request)
        {
            var id = Repository.AddBook(request.ISBN, request.BookName, request.Author, request.Edition, request.Publisher, request.Summary);
            return new AddBookResponse { ISBN = id };
        }

        public object Get(Books request)
        {
            return new BooksResponse{ books = Repository.GetBooks()};
        }

    }

    public class BooksResponse
    {
        public IEnumerable<Book> books { get; set; }
    }

    [Route("/books", "GET")]
    public class Books
    {
    } 

    [Route("/books", "POST")]
    public class AddBook
    {
        public long ISBN { get; set; }
        public string BookName { get; set; }
        public string Author { get; set; }
        public string Edition { get; set; }
        public string Publisher { get; set; }
        public string Summary { get; set; }
        public int InStock { get; set; }
    }


    public class AddBookResponse
    {
        public long ISBN { get; set; }
    }

Repository.cs代码:

 public interface IRepository
    {

        long AddBook(long ISBN, string BookName, string Author, string Edition, string Publisher, string Summary);
        IEnumerable<Book> GetBooks();
        Book GetBooks(long isbn);
        void UpdateStock(Book book);

    }

    public class Repository : IRepository
    {
        IRedisClientsManager RedisManager { get; set; }

        public Repository(IRedisClientsManager redisManager)
        {
            RedisManager = redisManager;
        }

        public IEnumerable<Book> GetBooks()
        {
            using (var redisClient = RedisManager.GetClient())
            {
                var redisUsers = redisClient.As<Book>();
                return redisUsers.GetAll();
            }
        }

        public Book GetBooks(long isbn)
        {
            using (var redisClient = RedisManager.GetClient())
            {
                var redisUsers = redisClient.As<Book>();
                return redisUsers.GetById(isbn);
            }
        }


        public long AddBook(long isbn, string bookName, string author, string edition, string publisher, string summary)
        {
            using (var redisClient = RedisManager.GetClient())
            {
                var redisUsers = redisClient.As<Book>();


                if(redisUsers.GetById(isbn) !=null)
                {
                    var book = GetBooks(isbn);
                    book.InStock++;
                    UpdateStock(book);
                    return isbn;
                }
                else
                {
                    var book = new Book() { Id = isbn, BookName = bookName, Author = author, Edition = edition, Publisher = publisher, Summary = summary, InStock = 1 };
                    redisUsers.Store(book);
                    return isbn;
                }

            }
        }


        public void UpdateStock(Book book)
        {
            using (var redisClient = RedisManager.GetClient())
            {
                var redisUsers = redisClient.As<Book>();
                redisUsers.Store(book);
            };
        }
    }

HomeController.cs代码:

  public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ViewResult Index(int? page)
        {
            using (var redisClient = new RedisClient("127.0.0.1", 6379, "123456", 1))
            {
                var pageIndex = page ?? 1;
                var pageSize = 20;
                var redisUsers = redisClient.As<Book>();
                var books = redisUsers.GetAll().OrderByDescending(a => a.Id).ToPagedList(pageIndex, pageSize);
                ViewBag.pageOfBooks = books;
                return View();
            }   
        }
    }

AdminController.cs代码:

   public class AdminController : Controller
    {
        private readonly static string getBookInfoUri = "http://isbndb.com/api/v2/json/KWC08NFB/book/";
        //http://isbndb.com/api/v2/json/[your-api-key]/book/9780849303159 


        // GET: /Admin/
        public ActionResult Index()
        {
            using (var redisClient = new RedisClient("127.0.0.1",6379,"123456",1))
            {
                var redisUsers = redisClient.As<Book>();
                ViewBag.pageOfBooks = redisUsers.GetAll();
                return View();
            }
        }

        public ActionResult PersonList()
        {
            using (var redisClient = new RedisClient("127.0.0.1", 6379, "123456", 1))
            {
                var redisPerson = redisClient.As<Person>();
                ViewBag.pageOfPersons = redisPerson.GetAll();
                return View();
            }
        }

        //[HttpPost]
        public ActionResult CreateFromId(string isbn)
        {
            string fullUri = getBookInfoUri + isbn;

            HttpWebRequest webRequest = GetWebRequest(fullUri);
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            string jsonResponse = string.Empty;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                jsonResponse = sr.ReadToEnd();
            }

            JObject o = JObject.Parse(jsonResponse);


            Book newBook = new Book();
            newBook.Id = long.Parse(isbn);
            newBook.BookName = (string)o["data"][0]["title"];
            newBook.Author = (string)o["data"][0]["author_data"][0]["name"];
            newBook.Edition = (string)o["data"][0]["edition_info"];
            newBook.Publisher = (string)o["data"][0]["publisher_text"];
            newBook.Summary = (string)o["data"][0]["summary"];

            using (var redisClient = new RedisClient("127.0.0.1", 6379, "123456", 1))
            {
                var redisUsers = redisClient.As<Book>();
                //添加单条数据
                redisUsers.Store(newBook);
                //添加多条数据
                //redisUsers.StoreAll(ListBook);

                //查询
                //Linq支持
                ViewBag.pageOfBooks = redisUsers.GetAll();
                //return View();
            }
            return View("Index");


        }

        public ActionResult CreatePerson()
        {
            Person p1 = new Person() { Id = 1, Name = "刘备" };
            Person p2 = new Person() { Id = 2, Name = "关羽" };
            Person p3 = new Person() { Id = 3, Name = "张飞" };
            Person p4 = new Person() { Id = 4, Name = "曹操" };
            Person p5 = new Person() { Id = 5, Name = "典韦" };
            Person p6 = new Person() { Id = 6, Name = "郭嘉" };
            List<Person> ListPerson = new List<Person>() { p2, p3, p4, p5, p6 };

            using (IRedisClient RClient = new RedisClient("127.0.0.1", 6379, "123456", 1))
            {
                IRedisTypedClient<Person> IRPerson = RClient.As<Person>();
                IRPerson.DeleteAll();

                //------------------------------------------添加--------------------------------------------

                //添加单条数据
                IRPerson.Store(p1);
                //添加多条数据
                IRPerson.StoreAll(ListPerson);

                //------------------------------------------查询--------------------------------------------

                //Linq支持
                Response.Write(IRPerson.GetAll().Where(m => m.Id == 1).First().Name);       //刘备
                //注意,用IRedisTypedClient的对象IRPerson的Srore()添加的才能用IRPerson()方法读取
                Response.Write(IRPerson.GetAll().First(m => m.Id == 2).Name);       //关羽

                //------------------------------------------删除--------------------------------------------

                /*
                IRPerson.Delete(p1);    //删除 刘备
                Response.Write(IRPerson.GetAll().Count());      //5
                IRPerson.DeleteById(2); //删除 关羽
                Response.Write(IRPerson.GetAll().Count());      //4
                IRPerson.DeleteByIds(new List<int> { 3, 4 });    //删除张飞 曹操
                Response.Write(IRPerson.GetAll().Count());      //2
                IRPerson.DeleteAll();   //全部删除
                Response.Write(IRPerson.GetAll().Count());      //0
                */
            }

            return Content("");
        }

        [HttpPost]
        public ActionResult Create(Book bookInfo)
        {


            return RedirectToAction("Index");


        }

        private static HttpWebRequest GetWebRequest(string formattedUri)
        {
            Uri serviceUri = new Uri(formattedUri, UriKind.Absolute);
            return (HttpWebRequest)System.Net.WebRequest.Create(serviceUri);
        }

    }

Admin视图文件夹:Index.cshtml内容:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Admin</h2>


<table>
    <tr>
        <th>
            ISBN
        </th>
        <th>
            Book Name
        </th>
        <th>
            Author
        </th>
        <th>
            Edition
        </th>
        <th>
            Number In Stock
        </th>
        <th></th>
    </tr>

@foreach (var item in ViewBag.pageOfBooks)
{
    <tr>
        <td>
            @item.Id
        </td>
        <td>
            @item.BookName
        </td>
        <td>
            @item.Author
        </td>
        <td>
            @item.Edition
        </td>
         <td>
            @item.InStock
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

</table>

PersonList.cshtml内容:

@model dynamic
@{
    ViewBag.Title = "Person";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Admin</h2>

<table>
    <tr>
        <th>
            ID
        </th>
        <th>
            名字
        </th>
        <th>
            功能
        </th>

    </tr>

    @foreach (var item in ViewBag.pageOfPersons)
    {
        <tr>
            <td>
                @item.Id
            </td>
            <td>
                @item.Name
            </td>
            <td>
                @*@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })*@
            </td>
        </tr>
    }
</table>

Home视图文件夹:Index.cshtml内容:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using PagedList.Mvc;
@using PagedList;
           @foreach (var item in ViewBag.pageOfBooks)
           {
               <div class ="bookSmall">
                   <h3>@item.BookName</h3>
                   <p>@item.Author</p>
                   <p>@item.Edition</p>
                   <p>@item.InStock</p>
                   @Html.ActionLink("More Details", "Details", new { Id = item.Id})
               </div>
           }

运行结果如图: